e154588a10e48bd39812568dbeb60e015c05ed4a
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / operations / DmiDataOperationsSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
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  *
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.ncmp.api.impl.operations
23
24 import com.fasterxml.jackson.databind.ObjectMapper
25 import org.onap.cps.events.EventsPublisher
26 import org.onap.cps.ncmp.api.impl.config.NcmpConfiguration
27 import org.onap.cps.ncmp.api.impl.exception.HttpClientRequestException
28 import org.onap.cps.ncmp.api.impl.utils.DmiServiceUrlBuilder
29 import org.onap.cps.ncmp.api.impl.utils.context.CpsApplicationContext
30 import org.onap.cps.ncmp.api.models.DataOperationRequest
31 import org.onap.cps.ncmp.events.async1_0_0.DataOperationEvent
32 import org.onap.cps.ncmp.utils.TestUtils
33 import org.onap.cps.utils.JsonObjectMapper
34 import org.spockframework.spring.SpringBean
35 import org.springframework.beans.factory.annotation.Autowired
36 import org.springframework.boot.test.context.SpringBootTest
37 import org.springframework.http.HttpStatus
38 import org.springframework.http.ResponseEntity
39 import org.springframework.test.context.ContextConfiguration
40 import spock.lang.Shared
41
42 import java.util.concurrent.TimeoutException
43
44 import static org.onap.cps.ncmp.api.NcmpResponseStatus.DMI_SERVICE_NOT_RESPONDING
45 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNABLE_TO_READ_RESOURCE_DATA
46 import static org.onap.cps.ncmp.api.impl.events.mapper.CloudEventMapper.toTargetEvent
47 import static org.onap.cps.ncmp.api.impl.operations.DatastoreType.PASSTHROUGH_OPERATIONAL
48 import static org.onap.cps.ncmp.api.impl.operations.DatastoreType.PASSTHROUGH_RUNNING
49 import static org.onap.cps.ncmp.api.impl.operations.OperationType.CREATE
50 import static org.onap.cps.ncmp.api.impl.operations.OperationType.READ
51 import static org.onap.cps.ncmp.api.impl.operations.OperationType.UPDATE
52
53 @SpringBootTest
54 @ContextConfiguration(classes = [EventsPublisher, CpsApplicationContext, NcmpConfiguration.DmiProperties, DmiDataOperations])
55 class DmiDataOperationsSpec extends DmiOperationsBaseSpec {
56
57     @SpringBean
58     DmiServiceUrlBuilder dmiServiceUrlBuilder = Mock()
59     def dmiServiceBaseUrl = "${dmiServiceName}/dmi/v1/ch/${cmHandleId}/data/ds/ncmp-datastore:"
60     def NO_TOPIC = null
61     def NO_REQUEST_ID = null
62     def NO_AUTH_HEADER = null
63     @Shared
64     def OPTIONS_PARAM = '(a=1,b=2)'
65
66     @SpringBean
67     JsonObjectMapper spiedJsonObjectMapper = Spy(new JsonObjectMapper(new ObjectMapper()))
68
69     @Autowired
70     DmiDataOperations objectUnderTest
71
72     @SpringBean
73     EventsPublisher eventsPublisher = Stub()
74
75     def 'call get resource data for #expectedDatastoreInUrl from DMI without topic #scenario.'() {
76         given: 'a cm handle for #cmHandleId'
77             mockYangModelCmHandleRetrieval(dmiProperties)
78         and: 'a positive response from DMI service when it is called with the expected parameters'
79             def responseFromDmi = new ResponseEntity<Object>(HttpStatus.OK)
80             def expectedUrl = dmiServiceBaseUrl + "${expectedDatastoreInUrl}?resourceIdentifier=${resourceIdentifier}${expectedOptionsInUrl}"
81             mockDmiRestClient.postOperationWithJsonData(expectedUrl, expectedJson, READ, NO_AUTH_HEADER) >> responseFromDmi
82             dmiServiceUrlBuilder.getDmiDatastoreUrl(_, _) >> expectedUrl
83         when: 'get resource data is invoked'
84             def result = objectUnderTest.getResourceDataFromDmi(dataStore.datastoreName, cmHandleId, resourceIdentifier,
85                     options, NO_TOPIC, NO_REQUEST_ID, NO_AUTH_HEADER)
86         then: 'the result is the response from the DMI service'
87             assert result == responseFromDmi
88         where: 'the following parameters are used'
89             scenario                               | dmiProperties               | dataStore               | options       || expectedJson                                                 | expectedDatastoreInUrl    | expectedOptionsInUrl
90             'without properties'                   | []                          | PASSTHROUGH_OPERATIONAL | OPTIONS_PARAM || '{"operation":"read","cmHandleProperties":{}}'               | 'passthrough-operational' | '&options=(a=1,b=2)'
91             'with properties'                      | [yangModelCmHandleProperty] | PASSTHROUGH_OPERATIONAL | OPTIONS_PARAM || '{"operation":"read","cmHandleProperties":{"prop1":"val1"}}' | 'passthrough-operational' | '&options=(a=1,b=2)'
92             'null options'                         | [yangModelCmHandleProperty] | PASSTHROUGH_OPERATIONAL | null          || '{"operation":"read","cmHandleProperties":{"prop1":"val1"}}' | 'passthrough-operational' | ''
93             'empty options'                        | [yangModelCmHandleProperty] | PASSTHROUGH_OPERATIONAL | ''            || '{"operation":"read","cmHandleProperties":{"prop1":"val1"}}' | 'passthrough-operational' | ''
94             'datastore running without properties' | []                          | PASSTHROUGH_RUNNING     | OPTIONS_PARAM || '{"operation":"read","cmHandleProperties":{}}'               | 'passthrough-running'     | '&options=(a=1,b=2)'
95             'datastore running with properties'    | [yangModelCmHandleProperty] | PASSTHROUGH_RUNNING     | OPTIONS_PARAM || '{"operation":"read","cmHandleProperties":{"prop1":"val1"}}' | 'passthrough-running'     | '&options=(a=1,b=2)'
96     }
97
98     def 'Execute (async) data operation from DMI service.'() {
99         given: 'collection of yang model cm Handles and data operation request'
100             mockYangModelCmHandleCollectionRetrieval([yangModelCmHandleProperty])
101             def dataOperationBatchRequestJsonData = TestUtils.getResourceFileContent('dataOperationRequest.json')
102             def dataOperationRequest = spiedJsonObjectMapper.convertJsonString(dataOperationBatchRequestJsonData, DataOperationRequest.class)
103             dataOperationRequest.dataOperationDefinitions[0].cmHandleIds = [cmHandleId]
104         and: 'a positive response from DMI service when it is called with valid request parameters'
105             def responseFromDmi = new ResponseEntity<Object>(HttpStatus.ACCEPTED)
106             def expectedDmiBatchResourceDataUrl = "ncmp/v1/data/topic=my-topic-name"
107             def expectedBatchRequestAsJson = '{"operations":[{"operation":"read","operationId":"operational-14","datastore":"ncmp-datastore:passthrough-operational","options":"some option","resourceIdentifier":"some resource identifier","cmHandles":[{"id":"some-cm-handle","cmHandleProperties":{"prop1":"val1"}}]}]}'
108             mockDmiRestClient.postOperationWithJsonData(expectedDmiBatchResourceDataUrl, _, READ.operationName, NO_AUTH_HEADER) >> responseFromDmi
109             dmiServiceUrlBuilder.getDataOperationRequestUrl(_, _) >> expectedDmiBatchResourceDataUrl
110         when: 'get resource data for group of cm handles are invoked'
111             objectUnderTest.requestResourceDataFromDmi('my-topic-name', dataOperationRequest, 'requestId', NO_AUTH_HEADER)
112         then: 'the post operation was called and ncmp generated dmi request body json args'
113             1 * mockDmiRestClient.postOperationWithJsonData(expectedDmiBatchResourceDataUrl, expectedBatchRequestAsJson, READ, NO_AUTH_HEADER)
114     }
115
116     def 'Execute (async) data operation from DMI service for #scenario.'() {
117         given: 'data operation request body and dmi resource url'
118             def dmiDataOperation = DmiDataOperation.builder().operationId('some-operation-id').build()
119             dmiDataOperation.getCmHandles().add(CmHandle.builder().id('some-cm-handle-id').build())
120             def dmiDataOperationResourceDataUrl = "http://dmi-service-name:dmi-port/dmi/v1/data?topic=my-topic-name&requestId=some-request-id"
121             def actualDataOperationCloudEvent = null
122         when: 'exception occurs after sending request to dmi service'
123             objectUnderTest.handleTaskCompletionException(new Throwable(exception), dmiDataOperationResourceDataUrl, List.of(dmiDataOperation))
124         then: 'a cloud event is published'
125             eventsPublisher.publishCloudEvent('my-topic-name', 'some-request-id', _) >> { args -> actualDataOperationCloudEvent = args[2] }
126         and: 'the event contains the expected error details'
127             def eventDataValue = extractDataValue(actualDataOperationCloudEvent)
128             assert eventDataValue.operationId == dmiDataOperation.operationId
129             assert eventDataValue.ids == dmiDataOperation.cmHandles.id
130             assert eventDataValue.statusCode == responseCode.code
131             assert eventDataValue.statusMessage == responseCode.message
132         where: 'the following exceptions are occurred'
133             scenario                        | exception                                                                                                || responseCode
134             'http client request exception' | new HttpClientRequestException('error-message', 'error-details', HttpStatus.SERVICE_UNAVAILABLE.value()) || UNABLE_TO_READ_RESOURCE_DATA
135             'timeout exception'             | new TimeoutException()                                                                                   || DMI_SERVICE_NOT_RESPONDING
136     }
137
138     def 'call get all resource data.'() {
139         given: 'the system returns a cm handle with a sample property'
140             mockYangModelCmHandleRetrieval([yangModelCmHandleProperty])
141         and: 'a positive response from DMI service when it is called with the expected parameters'
142             def responseFromDmi = new ResponseEntity<Object>(HttpStatus.OK)
143             def expectedUrl = dmiServiceBaseUrl + "passthrough-operational?resourceIdentifier=/"
144             mockDmiRestClient.postOperationWithJsonData(expectedUrl, '{"operation":"read","cmHandleProperties":{"prop1":"val1"}}', READ, null) >> responseFromDmi
145             dmiServiceUrlBuilder.getDmiDatastoreUrl(_, _) >> expectedUrl
146         when: 'get resource data is invoked'
147             def result = objectUnderTest.getResourceDataFromDmi( PASSTHROUGH_OPERATIONAL.datastoreName, cmHandleId, NO_REQUEST_ID)
148         then: 'the result is the response from the DMI service'
149             assert result == responseFromDmi
150     }
151
152     def 'Write data for pass-through:running datastore in DMI.'() {
153         given: 'a cm handle for #cmHandleId'
154             mockYangModelCmHandleRetrieval([yangModelCmHandleProperty])
155         and: 'a positive response from DMI service when it is called with the expected parameters'
156             def expectedUrl = dmiServiceBaseUrl + "passthrough-running?resourceIdentifier=${resourceIdentifier}"
157             def expectedJson = '{"operation":"' + expectedOperationInUrl + '","dataType":"some data type","data":"requestData","cmHandleProperties":{"prop1":"val1"}}'
158             def responseFromDmi = new ResponseEntity<Object>(HttpStatus.OK)
159             dmiServiceUrlBuilder.getDmiDatastoreUrl(_, _) >> expectedUrl
160             mockDmiRestClient.postOperationWithJsonData(expectedUrl, expectedJson, operation, NO_AUTH_HEADER) >> responseFromDmi
161         when: 'write resource method is invoked'
162             def result = objectUnderTest.writeResourceDataPassThroughRunningFromDmi(cmHandleId, 'parent/child', operation, 'requestData', 'some data type', NO_AUTH_HEADER)
163         then: 'the result is the response from the DMI service'
164             assert result == responseFromDmi
165         where: 'the following operation is performed'
166             operation || expectedOperationInUrl
167             CREATE    || 'create'
168             UPDATE    || 'update'
169     }
170
171     def extractDataValue(actualDataOperationCloudEvent) {
172         return toTargetEvent(actualDataOperationCloudEvent, DataOperationEvent.class).data.responses[0]
173     }
174 }