6cf15066810cddcff8e25ec081e7c8e90dab379c
[cps.git] / cps-ncmp-rest / src / test / groovy / org / onap / cps / ncmp / rest / controller / NetworkCmProxyControllerSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Pantheon.tech
4  *  Modifications Copyright (C) 2021 highstreet technologies GmbH
5  *  Modifications Copyright (C) 2021-2022 Nordix Foundation
6  *  Modifications Copyright (C) 2021-2022 Bell Canada.
7  *  ================================================================================
8  *  Licensed under the Apache License, Version 2.0 (the "License");
9  *  you may not use this file except in compliance with the License.
10  *  You may obtain a copy of the License at
11  *
12  *        http://www.apache.org/licenses/LICENSE-2.0
13  *
14  *  Unless required by applicable law or agreed to in writing, software
15  *  distributed under the License is distributed on an "AS IS" BASIS,
16  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  *  See the License for the specific language governing permissions and
18  *  limitations under the License.
19  *
20  *  SPDX-License-Identifier: Apache-2.0
21  *  ============LICENSE_END=========================================================
22  */
23
24 package org.onap.cps.ncmp.rest.controller
25
26 import org.mapstruct.factory.Mappers
27 import org.onap.cps.ncmp.api.inventory.CmHandleState
28 import org.onap.cps.ncmp.api.inventory.CompositeState
29 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
30 import org.onap.cps.ncmp.rest.mapper.RestOutputCmHandleStateMapper
31 import spock.lang.Shared
32
33 import java.time.OffsetDateTime
34 import java.time.ZoneOffset
35 import java.time.format.DateTimeFormatter
36
37 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH
38 import static org.onap.cps.ncmp.api.inventory.CompositeState.DataStores
39 import static org.onap.cps.ncmp.api.inventory.CompositeState.LockReason
40 import static org.onap.cps.ncmp.api.inventory.CompositeState.Operational
41 import static org.onap.cps.ncmp.api.inventory.CompositeState.Running
42 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
43 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
44 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
45 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
46 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
47 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE
48 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE
49 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE
50
51 import com.fasterxml.jackson.databind.ObjectMapper
52 import org.onap.cps.TestUtils
53 import org.onap.cps.spi.model.ModuleReference
54 import org.onap.cps.utils.JsonObjectMapper
55 import org.onap.cps.ncmp.api.NetworkCmProxyDataService
56 import org.spockframework.spring.SpringBean
57 import org.springframework.beans.factory.annotation.Autowired
58 import org.springframework.beans.factory.annotation.Value
59 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
60 import org.springframework.http.HttpStatus
61 import org.springframework.http.MediaType
62 import org.springframework.test.web.servlet.MockMvc
63 import spock.lang.Specification
64
65 @WebMvcTest(NetworkCmProxyController)
66 class NetworkCmProxyControllerSpec extends Specification {
67
68     @Autowired
69     MockMvc mvc
70
71     @SpringBean
72     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
73
74     @SpringBean
75     ObjectMapper objectMapper = new ObjectMapper()
76
77     @SpringBean
78     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(objectMapper)
79
80     @SpringBean
81     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
82
83     @SpringBean
84     RestOutputCmHandleStateMapper restOutputCmHandleStateMapper = Mappers.getMapper(RestOutputCmHandleStateMapper)
85
86     def formattedDateAndTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
87         .format(OffsetDateTime.of(2022, 12, 31, 20, 30, 40, 1, ZoneOffset.UTC))
88
89     @Value('${rest.api.ncmp-base-path}/v1')
90     def ncmpBasePathV1
91
92     def requestBody = '{"some-key":"some-value"}'
93
94     @Shared
95     def NO_TOPIC = null
96     def NO_REQUEST_ID = null
97
98     def 'Get Resource Data from pass-through operational.'() {
99         given: 'resource data url'
100             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-operational" +
101                     "?resourceIdentifier=parent/child&options=(a=1,b=2)"
102         when: 'get data resource request is performed'
103             def response = mvc.perform(
104                     get(getUrl)
105                             .contentType(MediaType.APPLICATION_JSON)
106             ).andReturn().response
107         then: 'the NCMP data service is called with getResourceDataOperationalForCmHandle'
108             1 * mockNetworkCmProxyDataService.getResourceDataOperationalForCmHandle('testCmHandle',
109                     'parent/child',
110                     '(a=1,b=2)',
111                     NO_TOPIC,
112                     NO_REQUEST_ID)
113         and: 'response status is Ok'
114             response.status == HttpStatus.OK.value()
115     }
116
117     def 'Get Resource Data from #datastoreInUrl with #scenario.'() {
118         given: 'resource data url'
119             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
120                     "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
121         when: 'get data resource request is performed'
122             def response = mvc.perform(
123                     get(getUrl)
124                     .contentType(MediaType.APPLICATION_JSON)
125             ).andReturn().response
126         then: 'the NCMP data service is called with operational data for cm handle'
127             expectedNumberOfMethodExecutions
128                     * mockNetworkCmProxyDataService."${expectedMethodName}"('testCmHandle',
129                     'parent/child',
130                     '(a=1,b=2)',
131                     expectedTopicName,
132                     _)
133         then: 'response status is expected'
134             response.status == expectedHttpStatus
135         where: 'the following parameters are used'
136             scenario                               | datastoreInUrl            | topicQueryParam        || expectedTopicName | expectedMethodName                             | expectedNumberOfMethodExecutions | expectedHttpStatus
137             'url with valid topic'                 | 'passthrough-operational' | '&topic=my-topic-name' || 'my-topic-name'   | 'getResourceDataOperationalForCmHandle'        | 1                                | HttpStatus.OK.value()
138             'no topic in url'                      | 'passthrough-operational' | ''                     || NO_TOPIC          | 'getResourceDataOperationalForCmHandle'        | 1                                | HttpStatus.OK.value()
139             'null topic in url'                    | 'passthrough-operational' | '&topic=null'          || 'null'            | 'getResourceDataOperationalForCmHandle'        | 1                                | HttpStatus.OK.value()
140             'empty topic in url'                   | 'passthrough-operational' | '&topic=\"\"'          || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
141             'missing topic in url'                 | 'passthrough-operational' | '&topic='              || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
142             'blank topic value in url'             | 'passthrough-operational' | '&topic=\" \"'         || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
143             'invalid non-empty topic value in url' | 'passthrough-operational' | '&topic=1_5_*_#'       || null              | 'getResourceDataOperationalForCmHandle'        | 0                                | HttpStatus.BAD_REQUEST.value()
144             'url with valid topic'                 | 'passthrough-running'     | '&topic=my-topic-name' || 'my-topic-name'   | 'getResourceDataPassThroughRunningForCmHandle' | 1                                | HttpStatus.OK.value()
145             'no topic in url'                      | 'passthrough-running'     | ''                     || NO_TOPIC          | 'getResourceDataPassThroughRunningForCmHandle' | 1                                | HttpStatus.OK.value()
146             'null topic in url'                    | 'passthrough-running'     | '&topic=null'          || 'null'            | 'getResourceDataPassThroughRunningForCmHandle' | 1                                | HttpStatus.OK.value()
147             'empty topic in url'                   | 'passthrough-running'     | '&topic=\"\"'          || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
148             'missing topic in url'                 | 'passthrough-running'     | '&topic='              || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
149             'blank topic value in url'             | 'passthrough-running'     | '&topic=\" \"'         || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
150             'invalid non-empty topic value in url' | 'passthrough-running'     | '&topic=1_5_*_#'       || null              | 'getResourceDataPassThroughRunningForCmHandle' | 0                                | HttpStatus.BAD_REQUEST.value()
151     }
152
153     def 'Get Resource Data from pass-through running with #scenario value in resource identifier param.'() {
154         given: 'resource data url'
155             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
156                     "?resourceIdentifier=" + resourceIdentifier + "&options=(a=1,b=2)"
157         and: 'ncmp service returns json object'
158             mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
159                     resourceIdentifier,
160                     '(a=1,b=2)',
161                     NO_TOPIC,
162                     NO_REQUEST_ID) >> '{valid-json}'
163         when: 'get data resource request is performed'
164             def response = mvc.perform(
165                     get(getUrl)
166                             .contentType(MediaType.APPLICATION_JSON)
167             ).andReturn().response
168         then: 'response status is Ok'
169             response.status == HttpStatus.OK.value()
170         and: 'response contains valid object body'
171             response.getContentAsString() == '{valid-json}'
172         where: 'tokens are used in the resource identifier parameter'
173             scenario                       | resourceIdentifier
174             '/'                            | 'id/with/slashes'
175             '?'                            | 'idWith?'
176             ','                            | 'idWith,'
177             '='                            | 'idWith='
178             '[]'                           | 'idWith[]'
179             '? needs to be encoded as %3F' | 'idWith%3F'
180     }
181
182     def 'Update resource data from pass-through running.' () {
183         given: 'update resource data url'
184             def updateUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
185                 "?resourceIdentifier=parent/child"
186         when: 'update data resource request is performed'
187             def response = mvc.perform(
188                 put(updateUrl)
189                     .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
190             ).andReturn().response
191         then: 'ncmp service method to update resource is called'
192             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
193                 'parent/child', UPDATE, requestBody, 'application/json;charset=UTF-8')
194         and: 'the response status is OK'
195             response.status == HttpStatus.OK.value()
196     }
197
198     def 'Create Resource Data from pass-through running with #scenario.' () {
199         given: 'resource data url'
200             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
201                     "?resourceIdentifier=parent/child"
202             def requestBody = '{"some-key":"some-value"}'
203         when: 'create resource request is performed'
204             def response = mvc.perform(
205                     post(url)
206                             .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
207             ).andReturn().response
208         then: 'ncmp service method to create resource called'
209             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
210                 'parent/child', CREATE, requestBody, 'application/json;charset=UTF-8')
211         and: 'resource is created'
212             response.status == HttpStatus.CREATED.value()
213     }
214
215     def 'Get module references for the given dataspace and cm handle.' () {
216         given: 'get module references url'
217             def getUrl = "$ncmpBasePathV1/ch/some-cmhandle/modules"
218         when: 'get module resource request is performed'
219             def response =mvc.perform(get(getUrl)).andReturn().response
220         then: 'ncmp service method to get yang resource module references is called'
221             mockNetworkCmProxyDataService.getYangResourcesModuleReferences('some-cmhandle')
222                     >> [new ModuleReference(moduleName: 'some-name1',revision: '2021-10-03')]
223         and: 'response contains an array with the module name and revision'
224             response.getContentAsString() == '[{"moduleName":"some-name1","revision":"2021-10-03"}]'
225         and: 'response returns an OK http code'
226             response.status == HttpStatus.OK.value()
227     }
228
229     def 'Retrieve cm handles.'() {
230         given: 'an endpoint and json data'
231             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
232             String jsonString = TestUtils.getResourceFileContent('cmhandle-search.json')
233         and: 'the service method is invoked with module names and returns two cm handle ids'
234             mockNetworkCmProxyDataService.executeCmHandleHasAllModulesSearch(['module1', 'module2']) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
235         when: 'the searches api is invoked'
236             def response = mvc.perform(post(searchesEndpoint)
237                     .contentType(MediaType.APPLICATION_JSON)
238                     .content(jsonString)).andReturn().response
239         then: 'response status returns OK'
240             response.status == HttpStatus.OK.value()
241         and: 'the expected response content is returned'
242             response.contentAsString == '{"cmHandles":[{"cmHandleId":"some-cmhandle-id1"},{"cmHandleId":"some-cmhandle-id2"}]}'
243     }
244
245     def 'Get Cm Handle details by Cm Handle id.'() {
246         given: 'an endpoint and a cm handle'
247             def cmHandleDetailsEndpoint = "$ncmpBasePathV1/ch/some-cm-handle"
248         and: 'an existing ncmp service cm handle'
249             def cmHandleId = 'some-cm-handle'
250             def dmiProperties = [ prop:'some DMI property' ]
251             def publicProperties = [ "public prop":'some public property' ]
252             def compositeState = new CompositeState(cmhandleState: CmHandleState.ADVISED,
253                 lockReason: LockReason.builder().reason('LOCKED_OTHER').details("lock-misbehaving-details").build(),
254                 lastUpdateTime: formattedDateAndTime.toString(),
255                 dataSyncEnabled: false,
256                 dataStores: dataStores())
257             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: dmiProperties, publicProperties: publicProperties, compositeState: compositeState)
258         and: 'the service method is invoked with the cm handle id'
259             1 * mockNetworkCmProxyDataService.getNcmpServiceCmHandle('some-cm-handle') >> ncmpServiceCmHandle
260         when: 'the cm handle details api is invoked'
261             def response = mvc.perform(get(cmHandleDetailsEndpoint)).andReturn().response
262         then: 'the correct response is returned'
263             response.status == HttpStatus.OK.value()
264         and: 'the response returns public properties and the correct cm handle states'
265             response.contentAsString.contains('publicCmHandleProperties')
266             response.contentAsString.contains('LOCKED_OTHER')
267             response.contentAsString.contains('lock-misbehaving-details')
268             response.contentAsString.contains('ADVISED')
269             response.contentAsString.contains('NONE_REQUESTED')
270             response.contentAsString.contains('2022-12-31T20:30:40.000+0000')
271         and: 'the content does not contain dmi properties'
272             !response.contentAsString.contains("some DMI property")
273     }
274
275     def 'Get Cm Handle public properties by Cm Handle id.' () {
276         given: 'a cm handle properties endpoint'
277             def cmHandlePropertiesEndpoint = "$ncmpBasePathV1/ch/some-cm-handle/properties"
278         and: 'some cm handle public properties'
279             def publicProperties =  [ 'public prop':'some public property' ]
280         and: 'the service method is invoked with the cm handle id returning the cm handle public properties'
281             1 * mockNetworkCmProxyDataService.getCmHandlePublicProperties('some-cm-handle') >> publicProperties
282         when: 'the cm handle properties api is invoked'
283             def response = mvc.perform(get(cmHandlePropertiesEndpoint)).andReturn().response
284         then: 'the correct response is returned'
285             response.status == HttpStatus.OK.value()
286         and: 'the response returns public properties and the correct properties'
287             response.contentAsString.equals('{"publicCmHandleProperties":[{"public prop":"some public property"}]}')
288     }
289
290     def 'Call execute cm handle searches with unrecognized condition name.'() {
291         given: 'an endpoint and json data'
292             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
293             String jsonString = TestUtils.getResourceFileContent('invalid-cmhandle-search.json')
294         when: 'the searches api is invoked'
295             def response = mvc.perform(post(searchesEndpoint)
296                     .contentType(MediaType.APPLICATION_JSON)
297                     .content(jsonString)).andReturn().response
298         then: 'an empty cm handle identifier is returned'
299             response.contentAsString == '{"cmHandles":[]}'
300     }
301
302     def 'Query for cm handles matching query parameters'() {
303         given: 'an endpoint and json data'
304             def searchesEndpoint = "$ncmpBasePathV1/data/ch/searches"
305             String jsonString = '{"publicCmHandleProperties": {"name": "Contact", "value": "newemailforstore@bookstore.com"}}'
306         and: 'the service method is invoked with module names and returns cm handle ids'
307             1 * mockNetworkCmProxyDataService.queryCmHandles(_) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
308         when: 'the searches api is invoked'
309             def response = mvc.perform(post(searchesEndpoint)
310                 .contentType(MediaType.APPLICATION_JSON)
311                 .content(jsonString)).andReturn().response
312         then: 'cm handle ids are returned'
313             response.contentAsString == '["some-cmhandle-id1","some-cmhandle-id2"]'
314     }
315
316     def 'Query for cm handles with invalid request payload'() {
317         when: 'the searches api is invoked'
318             def searchesEndpoint = "$ncmpBasePathV1/data/ch/searches"
319             def invalidInputData = '{invalidJson}'
320             def response = mvc.perform(post(searchesEndpoint)
321                     .contentType(MediaType.APPLICATION_JSON)
322                     .content(invalidInputData)).andReturn().response
323         then: 'BAD_REQUEST is returned'
324             response.getStatus() == 400
325     }
326
327     def 'Patch resource data in pass-through running datastore.' () {
328         given: 'patch resource data url'
329             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
330                     "?resourceIdentifier=parent/child"
331         when: 'patch data resource request is performed'
332             def response = mvc.perform(
333                     patch(url)
334                             .contentType(MediaType.APPLICATION_JSON)
335                             .accept(MediaType.APPLICATION_JSON).content(requestBody)
336             ).andReturn().response
337         then: 'ncmp service method to update resource is called'
338             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
339                     'parent/child', PATCH, requestBody, 'application/json;charset=UTF-8')
340         and: 'the response status is OK'
341             response.status == HttpStatus.OK.value()
342     }
343
344     def 'Delete resource data in pass-through running datastore.' () {
345         given: 'delete resource data url'
346             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
347                      "?resourceIdentifier=parent/child"
348         when: 'delete data resource request is performed'
349             def response = mvc.perform(
350                 delete(url).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn().response
351         then: 'the ncmp service method to delete resource is called (with null as body)'
352             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
353                 'parent/child', DELETE, null, 'application/json;charset=UTF-8')
354         and: 'the response is No Content'
355             response.status == HttpStatus.NO_CONTENT.value()
356     }
357
358     def 'Get resource data from DMI with valid topic i.e. async request for #scenario'() {
359         given: 'resource data url'
360             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
361                     "?resourceIdentifier=parent/child&options=(a=1,b=2)&topic=my-topic-name"
362         when: 'get data resource request is performed'
363             def response = mvc.perform(
364                     get(getUrl)
365                             .contentType(MediaType.APPLICATION_JSON)
366                             .accept(MediaType.APPLICATION_JSON_VALUE)
367             ).andReturn().response
368         then: 'async request id is generated'
369             assert response.contentAsString.contains("requestId")
370         where: 'the following parameters are used'
371             scenario                   | datastoreInUrl
372             ':passthrough-operational' | 'passthrough-operational'
373             ':passthrough-running'     | 'passthrough-running'
374     }
375
376     def dataStores() {
377         DataStores.builder()
378             .operationalDataStore(Operational.builder()
379                 .syncState('NONE_REQUESTED')
380                 .lastSyncTime(formattedDateAndTime.toString()).build())
381             .runningDataStore(Running.builder()
382                 .syncState('NONE_REQUESTED')
383                 .lastSyncTime(formattedDateAndTime.toString()).build())
384             .build()
385     }
386
387 }
388