2  *  ============LICENSE_START=======================================================
 
   3  *  Copyright (C) 2022 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
 
   9  *        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.
 
  17  *  SPDX-License-Identifier: Apache-2.0
 
  18  *  ============LICENSE_END=========================================================
 
  21 package org.onap.cps.ncmp.api.impl
 
  23 import org.onap.cps.cpspath.parser.PathParsingException
 
  24 import org.onap.cps.ncmp.api.inventory.CmHandleQueries
 
  25 import org.onap.cps.ncmp.api.inventory.CmHandleQueriesImpl
 
  26 import org.onap.cps.ncmp.api.inventory.InventoryPersistence
 
  27 import org.onap.cps.ncmp.api.models.CmHandleQueryServiceParameters
 
  28 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
 
  29 import org.onap.cps.spi.FetchDescendantsOption
 
  30 import org.onap.cps.spi.exceptions.DataInUseException
 
  31 import org.onap.cps.spi.exceptions.DataValidationException
 
  32 import org.onap.cps.spi.model.Anchor
 
  33 import org.onap.cps.spi.model.ConditionProperties
 
  34 import org.onap.cps.spi.model.DataNode
 
  35 import spock.lang.Specification
 
  37 import java.util.stream.Collectors
 
  39 class NetworkCmProxyCmHandlerQueryServiceSpec extends Specification {
 
  41     def cmHandleQueries = Mock(CmHandleQueries)
 
  42     def partiallyMockedCmHandleQueries = Spy(CmHandleQueriesImpl)
 
  43     def mockInventoryPersistence = Mock(InventoryPersistence)
 
  45     def static someCmHandleDataNode = new DataNode(xpath: '/dmi-registry/cm-handles[@id=\'some-cmhandle-id\']', leaves: ['id':'some-cmhandle-id'])
 
  46     def dmiRegistry = new DataNode(xpath: '/dmi-registry', childDataNodes: createDataNodeList(['PNFDemo1', 'PNFDemo2', 'PNFDemo3', 'PNFDemo4']))
 
  48     static def queryResultCmHandleMap = createCmHandleMap(['H1', 'H2'])
 
  50     def objectUnderTest = new NetworkCmProxyCmHandlerQueryServiceImpl(cmHandleQueries, mockInventoryPersistence)
 
  51     def objectUnderTestSpy = new NetworkCmProxyCmHandlerQueryServiceImpl(partiallyMockedCmHandleQueries, mockInventoryPersistence)
 
  53     def 'Retrieve cm handles with cpsPath when combined with no Module Query.'() {
 
  54         given: 'a cmHandleWithCpsPath condition property'
 
  55             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
  56             def conditionProperties = createConditionProperties('cmHandleWithCpsPath', [['cpsPath' : '/some/cps/path']])
 
  57             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
 
  58         and: 'cmHandleQueries returns a non null query result'
 
  59             cmHandleQueries.queryCmHandleDataNodesByCpsPath('/some/cps/path', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> [new DataNode(leaves: ['id':'some-cmhandle-id'])]
 
  60         and: 'CmHandleQueries returns cmHandles with the relevant query result'
 
  61             cmHandleQueries.combineCmHandleQueries(*_) >> ['PNFDemo1': new NcmpServiceCmHandle(cmHandleId: 'PNFDemo1'), 'PNFDemo3': new NcmpServiceCmHandle(cmHandleId: 'PNFDemo3')]
 
  62         when: 'the query is executed for both cm handle ids and details'
 
  63             def returnedCmHandlesJustIds = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
 
  64             def returnedCmHandlesWithData = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
 
  65         then: 'the correct expected cm handles ids are returned'
 
  66             returnedCmHandlesJustIds == ['PNFDemo1', 'PNFDemo3'] as Set
 
  67         and: 'the correct ncmp service cm handles are returned'
 
  68             returnedCmHandlesWithData.stream().map(CmHandle -> CmHandle.cmHandleId).collect(Collectors.toSet()) == ['PNFDemo1', 'PNFDemo3'] as Set
 
  71     def 'Retrieve cm handles with cpsPath where #scenario.'() {
 
  72         given: 'a cmHandleWithCpsPath condition property'
 
  73             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
  74             def conditionProperties = createConditionProperties('cmHandleWithCpsPath', [['cpsPath' : '/some/cps/path']])
 
  75             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
 
  76         and: 'cmHandleQueries throws a path parsing exception'
 
  77             cmHandleQueries.queryCmHandleDataNodesByCpsPath('/some/cps/path', FetchDescendantsOption.INCLUDE_ALL_DESCENDANTS) >> { throw thrownException }
 
  78         when: 'the query is executed for both cm handle ids and details'
 
  79             objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
 
  80             objectUnderTest.queryCmHandles(cmHandleQueryParameters)
 
  81         then: 'a data validation exception is thrown'
 
  82             thrown(expectedException)
 
  83         where: 'the following data is used'
 
  84             scenario                           | thrownException                                          || expectedException
 
  85             'a PathParsingException is thrown' | new PathParsingException('some message', 'some details') || DataValidationException
 
  86             'any other Exception is thrown'    | new DataInUseException('some message', 'some details')   || DataInUseException
 
  89     def 'Query cm handles with public properties when combined with empty modules query result.'() {
 
  90         given: 'a public properties condition property'
 
  91             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
  92             def conditionProperties = createConditionProperties('hasAllProperties', [['some-property-key': 'some-property-value']])
 
  93             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
 
  94         and: 'CmHandleQueries returns cmHandles with the relevant query result'
 
  95             cmHandleQueries.combineCmHandleQueries(*_) >> ['PNFDemo1': new NcmpServiceCmHandle(cmHandleId: 'PNFDemo1'), 'PNFDemo3': new NcmpServiceCmHandle(cmHandleId: 'PNFDemo3')]
 
  96         when: 'the query is executed for both cm handle ids and details'
 
  97             def returnedCmHandlesJustIds = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
 
  98             def returnedCmHandlesWithData = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
 
  99         then: 'the correct expected cm handles ids are returned'
 
 100             returnedCmHandlesJustIds == ['PNFDemo1', 'PNFDemo3'] as Set
 
 101         and: 'the correct cm handle data objects are returned'
 
 102             returnedCmHandlesWithData.stream().map(dataNode -> dataNode.cmHandleId).collect(Collectors.toSet()) == ['PNFDemo1', 'PNFDemo3'] as Set
 
 105     def 'Retrieve cm handles with module names when #scenario from query.'() {
 
 106         given: 'a modules condition property'
 
 107             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
 108             def conditionProperties = createConditionProperties('hasAllModules', [['moduleName': 'some-module-name']])
 
 109             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
 
 110         and: 'null is returned from the state and public property queries'
 
 111             cmHandleQueries.combineCmHandleQueries(*_) >> null
 
 112         and: '#scenario from the modules query'
 
 113             mockInventoryPersistence.queryAnchors(*_) >> returnedAnchors
 
 114         and: 'the same cmHandles are returned from the persistence service layer'
 
 115             returnedAnchors.size() * mockInventoryPersistence.getDataNode(*_) >> returnedCmHandles
 
 116         when: 'the query is executed for both cm handle ids and details'
 
 117             def returnedCmHandlesJustIds = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
 
 118             def returnedCmHandlesWithData = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
 
 119         then: 'the correct expected cm handles ids are returned'
 
 120             returnedCmHandlesJustIds == expectedCmHandleIds as Set
 
 121         and: 'the correct cm handle data objects are returned'
 
 122             returnedCmHandlesWithData.stream().map(dataNode -> dataNode.cmHandleId).collect(Collectors.toSet()) == expectedCmHandleIds as Set
 
 123         where: 'the following data is used'
 
 124             scenario                  | returnedAnchors                        | returnedCmHandles    || expectedCmHandleIds
 
 125             'One anchor returned'     | [new Anchor(name: 'some-cmhandle-id')] | someCmHandleDataNode || ['some-cmhandle-id']
 
 126             'No anchors are returned' | []                                     | null                 || []
 
 129     def 'Retrieve cm handles with combined queries when #scenario.'() {
 
 130         given: 'all condition properties used'
 
 131             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
 132             def conditionPubProps = createConditionProperties('hasAllProperties', [['some-property-key': 'some-property-value']])
 
 133             def conditionModules = createConditionProperties('hasAllModules', [['moduleName': 'some-module-name']])
 
 134             def conditionState = createConditionProperties('cmHandleWithCpsPath', [['cpsPath' : '/some/cps/path']])
 
 135             cmHandleQueryParameters.setCmHandleQueryParameters([conditionPubProps, conditionModules, conditionState])
 
 136         and: 'cmHandles are returned from the state and public property combined queries'
 
 137             cmHandleQueries.combineCmHandleQueries(*_) >> combinedQueryMap
 
 138         and: 'cmHandles are returned from the module names query'
 
 139             mockInventoryPersistence.queryAnchors(['some-module-name']) >> anchorsForModuleQuery
 
 140         and: 'cmHandleQueries returns a datanode result'
 
 141             2 * cmHandleQueries.queryCmHandleDataNodesByCpsPath(*_) >> [someCmHandleDataNode]
 
 142         when: 'the query is executed for both cm handle ids and details'
 
 143             def returnedCmHandlesJustIds = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
 
 144             def returnedCmHandlesWithData = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
 
 145         then: 'the correct expected cm handles ids are returned'
 
 146             returnedCmHandlesJustIds == expectedCmHandleIds as Set
 
 147         and: 'the correct cm handle data objects are returned'
 
 148             returnedCmHandlesWithData.stream().map(dataNode -> dataNode.cmHandleId).collect(Collectors.toSet()) == expectedCmHandleIds as Set
 
 149         where: 'the following data is used'
 
 150             scenario                                 | combinedQueryMap                                                                                                           | anchorsForModuleQuery                                        || expectedCmHandleIds
 
 151             'combined and modules queries intersect' | ['PNFDemo1' : new NcmpServiceCmHandle(cmHandleId:'PNFDemo1')]                                                              | [new Anchor(name: 'PNFDemo1'), new Anchor(name: 'PNFDemo2')] || ['PNFDemo1']
 
 152             'only module query results exist'        | [:]                                                                                                                        | [new Anchor(name: 'PNFDemo1'), new Anchor(name: 'PNFDemo2')] || []
 
 153             'only combined query results exist'      | ['PNFDemo1' : new NcmpServiceCmHandle(cmHandleId:'PNFDemo1'), 'PNFDemo2' : new NcmpServiceCmHandle(cmHandleId:'PNFDemo2')] | []                                                           || []
 
 154             'neither queries return results'         | [:]                                                                                                                        | []                                                           || []
 
 155             'none intersect'                         | ['PNFDemo1' : new NcmpServiceCmHandle(cmHandleId:'PNFDemo1')]                                                              | [new Anchor(name: 'PNFDemo2')]                               || []
 
 158     def 'Retrieve cm handles when the query is empty.'() {
 
 159         given: 'We use an empty query'
 
 160             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
 161         and: 'the inventory persistence returns the dmi registry datanode with just ids'
 
 162             mockInventoryPersistence.getDataNode("/dmi-registry", FetchDescendantsOption.FETCH_DIRECT_CHILDREN_ONLY) >> dmiRegistry
 
 163         and: 'the inventory persistence returns the dmi registry datanode with data'
 
 164             mockInventoryPersistence.getDataNode("/dmi-registry") >> dmiRegistry
 
 165         when: 'the query is executed for both cm handle ids and details'
 
 166             def returnedCmHandlesJustIds = objectUnderTest.queryCmHandleIds(cmHandleQueryParameters)
 
 167             def returnedCmHandlesWithData = objectUnderTest.queryCmHandles(cmHandleQueryParameters)
 
 168         then: 'the correct expected cm handles are returned'
 
 169             returnedCmHandlesJustIds == ['PNFDemo1', 'PNFDemo2', 'PNFDemo3', 'PNFDemo4'] as Set
 
 170             returnedCmHandlesWithData.stream().map(d -> d.cmHandleId).collect(Collectors.toSet()) == ['PNFDemo1', 'PNFDemo2', 'PNFDemo3', 'PNFDemo4'] as Set
 
 174     def 'Retrieve all CMHandleIds for empty query parameters' () {
 
 175         given: 'We query without any parameters'
 
 176             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
 177         and: 'the inventoryPersistence returns all four CmHandleIds'
 
 178             mockInventoryPersistence.getDataNode(*_) >> dmiRegistry
 
 179         when: 'the query executed'
 
 180             def resultSet = objectUnderTest.queryCmHandleIdsForInventory(cmHandleQueryParameters)
 
 181         then: 'the size of the result list equals the size of all cmHandleIds.'
 
 182             resultSet.size() == 4
 
 185     def 'Retrieve CMHandleIds when #scenario.' () {
 
 186         given: 'a query object created with #condition'
 
 187             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
 188             def conditionProperties = createConditionProperties(conditionName, [['some-key': 'some-value']])
 
 189             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
 
 190         and: 'the inventoryPersistence returns different CmHandleIds'
 
 191             partiallyMockedCmHandleQueries.queryCmHandlePublicProperties(*_) >> cmHandlesWithMatchingPublicProperties
 
 192             partiallyMockedCmHandleQueries.queryCmHandleAdditionalProperties(*_) >> cmHandlesWithMatchingPrivateProperties
 
 193         when: 'the query executed'
 
 194             def result = objectUnderTestSpy.queryCmHandleIdsForInventory(cmHandleQueryParameters)
 
 195         then: 'the expected number of results are returned.'
 
 196             assert result.size() == expectedCmHandleIdsSize
 
 197         where: 'the following data is used'
 
 198             scenario                                          | conditionName                | cmHandlesWithMatchingPublicProperties | cmHandlesWithMatchingPrivateProperties || expectedCmHandleIdsSize
 
 199             'all properties, only public matching'            | 'hasAllProperties'           | queryResultCmHandleMap                |  null                                  || 2
 
 200             'all properties, no matching cm handles'          | 'hasAllProperties'           | [:]                                   |  [:]                                   || 0
 
 201             'additional properties, some matching cm handles' | 'hasAllAdditionalProperties' | [:]                                   | queryResultCmHandleMap                 || 2
 
 202             'additional properties, no matching cm handles'   | 'hasAllAdditionalProperties' | null                                  |  [:]                                   || 0
 
 205     def 'Retrieve CMHandleIds by different DMI properties with #scenario.' () {
 
 206         given: 'a query object created with dmi plugin as condition'
 
 207             def cmHandleQueryParameters = new CmHandleQueryServiceParameters()
 
 208             def conditionProperties = createConditionProperties('cmHandleWithDmiPlugin', [['some-key': 'some-value']])
 
 209             cmHandleQueryParameters.setCmHandleQueryParameters([conditionProperties])
 
 210         and: 'the inventoryPersistence returns different CmHandleIds'
 
 211             partiallyMockedCmHandleQueries.getCmHandlesByDmiPluginIdentifier(*_) >> cmHandleQueryResult
 
 212         when: 'the query executed'
 
 213             def result = objectUnderTestSpy.queryCmHandleIdsForInventory(cmHandleQueryParameters)
 
 214         then: 'the expected number of results are returned.'
 
 215             assert result.size() == expectedCmHandleIdsSize
 
 216         where: 'the following data is used'
 
 217             scenario       | cmHandleQueryResult             || expectedCmHandleIdsSize
 
 218             'some matches' | queryResultCmHandleMap.values() || 2
 
 219             'no matches'   | []                              || 0
 
 222     static def createCmHandleMap(cmHandleIds) {
 
 223         def cmHandleMap = [:]
 
 224         cmHandleIds.each{ cmHandleMap[it] = new NcmpServiceCmHandle(cmHandleId : it) }
 
 228     def createConditionProperties(String conditionName, List<Map<String, String>> conditionParameters) {
 
 229         return new ConditionProperties(conditionName : conditionName, conditionParameters : conditionParameters)
 
 232     def static createDataNodeList(dataNodeIds) {
 
 234         dataNodeIds.each{ dataNodes << new DataNode(xpath: "/dmi-registry/cm-handles[@id='${it}']", leaves: ['id':it]) }