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