Merge "CPS-1020 : DuplicatedYangResourceException error at parallel cmHandle registra...
[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 org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor
32 import spock.lang.Shared
33
34 import java.time.OffsetDateTime
35 import java.time.ZoneOffset
36 import java.time.format.DateTimeFormatter
37
38 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH
39 import static org.onap.cps.ncmp.api.inventory.CompositeState.DataStores
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     @SpringBean
87     CpsNcmpTaskExecutor spiedCpsTaskExecutor = Spy()
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 formattedDateAndTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
99         .format(OffsetDateTime.of(2022, 12, 31, 20, 30, 40, 1, ZoneOffset.UTC))
100
101     def 'Get Resource Data from pass-through operational.'() {
102         given: 'resource data url'
103             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-operational" +
104                     "?resourceIdentifier=parent/child&options=(a=1,b=2)"
105         when: 'get data resource request is performed'
106             def response = mvc.perform(
107                     get(getUrl)
108                             .contentType(MediaType.APPLICATION_JSON)
109             ).andReturn().response
110         then: 'the NCMP data service is called with getResourceDataOperationalForCmHandle'
111             1 * mockNetworkCmProxyDataService.getResourceDataOperationalForCmHandle('testCmHandle',
112                     'parent/child',
113                     '(a=1,b=2)',
114                     NO_TOPIC,
115                     NO_REQUEST_ID)
116         and: 'response status is Ok'
117             response.status == HttpStatus.OK.value()
118     }
119
120     def 'Get Resource Data from #datastoreInUrl with #scenario.'() {
121         given: 'resource data url'
122             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
123                     "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
124         when: 'get data resource request is performed'
125             def response = mvc.perform(
126                     get(getUrl).contentType(MediaType.APPLICATION_JSON)).andReturn().response
127         then: 'task executor is called appropriate number of times'
128             expectedNumberOfExecutorExecutions * spiedCpsTaskExecutor.executeTask(_, 2000)
129         and: 'response status is expected'
130             response.status == HttpStatus.OK.value()
131         where: 'the following parameters are used'
132             scenario                               | datastoreInUrl            | topicQueryParam        || expectedTopicName | expectedNumberOfExecutorExecutions
133             'url with valid topic'                 | 'passthrough-operational' | '&topic=my-topic-name' || 'my-topic-name'   | 1
134             'no topic in url'                      | 'passthrough-operational' | ''                     || NO_TOPIC          | 0
135             'null topic in url'                    | 'passthrough-operational' | '&topic=null'          || 'null'            | 1
136             'url with valid topic'                 | 'passthrough-running'     | '&topic=my-topic-name' || 'my-topic-name'   | 1
137             'no topic in url'                      | 'passthrough-running'     | ''                     || NO_TOPIC          | 0
138             'null topic in url'                    | 'passthrough-running'     | '&topic=null'          || 'null'            | 1
139     }
140
141     def 'Fail to get Resource Data from #datastoreInUrl when #scenario.'() {
142         given: 'resource data url'
143             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
144                 "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
145         when: 'get data resource request is performed'
146             def response = mvc.perform(
147                 get(getUrl).contentType(MediaType.APPLICATION_JSON)).andReturn().response
148         then: 'abad request is returned'
149             response.status == HttpStatus.BAD_REQUEST.value()
150         where: 'the following parameters are used'
151             scenario                               | datastoreInUrl            | topicQueryParam
152             'empty topic in url'                   | 'passthrough-operational' | '&topic=\"\"'
153             'missing topic in url'                 | 'passthrough-operational' | '&topic='
154             'blank topic value in url'             | 'passthrough-operational' | '&topic=\" \"'
155             'invalid non-empty topic value in url' | 'passthrough-operational' | '&topic=1_5_*_#'
156             'empty topic in url'                   | 'passthrough-running'     | '&topic=\"\"'
157             'missing topic in url'                 | 'passthrough-running'     | '&topic='
158             'blank topic value in url'             | 'passthrough-running'     | '&topic=\" \"'
159             'invalid non-empty topic value in url' | 'passthrough-running'     | '&topic=1_5_*_#'
160     }
161
162     def 'Get Resource Data from pass-through running with #scenario value in resource identifier param.'() {
163         given: 'resource data url'
164             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
165                     "?resourceIdentifier=" + resourceIdentifier + "&options=(a=1,b=2)"
166         and: 'ncmp service returns json object'
167             mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
168                     resourceIdentifier,
169                     '(a=1,b=2)',
170                     NO_TOPIC,
171                     NO_REQUEST_ID) >> '{valid-json}'
172         when: 'get data resource request is performed'
173             def response = mvc.perform(
174                     get(getUrl)
175                             .contentType(MediaType.APPLICATION_JSON)
176             ).andReturn().response
177         then: 'response status is Ok'
178             response.status == HttpStatus.OK.value()
179         and: 'response contains valid object body'
180             response.getContentAsString() == '{valid-json}'
181         where: 'tokens are used in the resource identifier parameter'
182             scenario                       | resourceIdentifier
183             '/'                            | 'id/with/slashes'
184             '?'                            | 'idWith?'
185             ','                            | 'idWith,'
186             '='                            | 'idWith='
187             '[]'                           | 'idWith[]'
188             '? needs to be encoded as %3F' | 'idWith%3F'
189     }
190
191     def 'Update resource data from pass-through running.' () {
192         given: 'update resource data url'
193             def updateUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
194                 "?resourceIdentifier=parent/child"
195         when: 'update data resource request is performed'
196             def response = mvc.perform(
197                 put(updateUrl)
198                     .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
199             ).andReturn().response
200         then: 'ncmp service method to update resource is called'
201             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
202                 'parent/child', UPDATE, requestBody, 'application/json;charset=UTF-8')
203         and: 'the response status is OK'
204             response.status == HttpStatus.OK.value()
205     }
206
207     def 'Create Resource Data from pass-through running with #scenario.' () {
208         given: 'resource data url'
209             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
210                     "?resourceIdentifier=parent/child"
211             def requestBody = '{"some-key":"some-value"}'
212         when: 'create resource request is performed'
213             def response = mvc.perform(
214                     post(url)
215                             .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
216             ).andReturn().response
217         then: 'ncmp service method to create resource called'
218             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
219                 'parent/child', CREATE, requestBody, 'application/json;charset=UTF-8')
220         and: 'resource is created'
221             response.status == HttpStatus.CREATED.value()
222     }
223
224     def 'Get module references for the given dataspace and cm handle.' () {
225         given: 'get module references url'
226             def getUrl = "$ncmpBasePathV1/ch/some-cmhandle/modules"
227         when: 'get module resource request is performed'
228             def response =mvc.perform(get(getUrl)).andReturn().response
229         then: 'ncmp service method to get yang resource module references is called'
230             mockNetworkCmProxyDataService.getYangResourcesModuleReferences('some-cmhandle')
231                     >> [new ModuleReference(moduleName: 'some-name1',revision: '2021-10-03')]
232         and: 'response contains an array with the module name and revision'
233             response.getContentAsString() == '[{"moduleName":"some-name1","revision":"2021-10-03"}]'
234         and: 'response returns an OK http code'
235             response.status == HttpStatus.OK.value()
236     }
237
238     def 'Retrieve cm handles.'() {
239         given: 'an endpoint and json data'
240             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
241             String jsonString = TestUtils.getResourceFileContent('cmhandle-search.json')
242         and: 'the service method is invoked with module names and returns two cm handle ids'
243             mockNetworkCmProxyDataService.executeCmHandleHasAllModulesSearch(['module1', 'module2']) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
244         when: 'the searches api is invoked'
245             def response = mvc.perform(post(searchesEndpoint)
246                     .contentType(MediaType.APPLICATION_JSON)
247                     .content(jsonString)).andReturn().response
248         then: 'response status returns OK'
249             response.status == HttpStatus.OK.value()
250         and: 'the expected response content is returned'
251             response.contentAsString == '{"cmHandles":[{"cmHandleId":"some-cmhandle-id1"},{"cmHandleId":"some-cmhandle-id2"}]}'
252     }
253
254     def 'Get Cm Handle details by Cm Handle id.'() {
255         given: 'an endpoint and a cm handle'
256             def cmHandleDetailsEndpoint = "$ncmpBasePathV1/ch/some-cm-handle"
257         and: 'an existing ncmp service cm handle'
258             def compositeState = new CompositeState(cmHandleState: CmHandleState.ADVISED,
259                 lastUpdateTime: formattedDateAndTime.toString(),
260                 dataStores: dataStores())
261             def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: 'some-cm-handle', compositeState: compositeState)
262         and: 'the service method is invoked with the cm handle id'
263             1 * mockNetworkCmProxyDataService.getNcmpServiceCmHandle('some-cm-handle') >> ncmpServiceCmHandle
264         when: 'the cm handle details api is invoked'
265             def response = mvc.perform(get(cmHandleDetailsEndpoint)).andReturn().response
266         then: 'the correct response is returned'
267             response.status == HttpStatus.OK.value()
268         and: 'the response returns the correct state and timestamp'
269             response.contentAsString.contains('some-cm-handle')
270             response.contentAsString.contains('ADVISED')
271             response.contentAsString.contains('2022-12-31T20:30:40.000+0000')
272     }
273
274     def 'Get Cm Handle public properties by Cm Handle id.' () {
275         given: 'a cm handle properties endpoint'
276             def cmHandlePropertiesEndpoint = "$ncmpBasePathV1/ch/some-cm-handle/properties"
277         and: 'some cm handle public properties'
278             def publicProperties =  [ 'public prop':'some public property' ]
279         and: 'the service method is invoked with the cm handle id returning the cm handle public properties'
280             1 * mockNetworkCmProxyDataService.getCmHandlePublicProperties('some-cm-handle') >> publicProperties
281         when: 'the cm handle properties api is invoked'
282             def response = mvc.perform(get(cmHandlePropertiesEndpoint)).andReturn().response
283         then: 'the correct response is returned'
284             response.status == HttpStatus.OK.value()
285         and: 'the response returns public properties and the correct properties'
286             response.contentAsString.equals('{"publicCmHandleProperties":[{"public prop":"some public property"}]}')
287     }
288
289     def 'Call execute cm handle searches with unrecognized condition name.'() {
290         given: 'an endpoint and json data'
291             def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
292             String jsonString = TestUtils.getResourceFileContent('invalid-cmhandle-search.json')
293         when: 'the searches api is invoked'
294             def response = mvc.perform(post(searchesEndpoint)
295                     .contentType(MediaType.APPLICATION_JSON)
296                     .content(jsonString)).andReturn().response
297         then: 'an empty cm handle identifier is returned'
298             response.contentAsString == '{"cmHandles":[]}'
299     }
300
301     def 'Query for cm handles matching query parameters'() {
302         given: 'an endpoint and json data'
303             def searchesEndpoint = "$ncmpBasePathV1/data/ch/searches"
304             String jsonString = '{"publicCmHandleProperties": {"name": "Contact", "value": "newemailforstore@bookstore.com"}}'
305         and: 'the service method is invoked with module names and returns cm handle ids'
306             1 * mockNetworkCmProxyDataService.queryCmHandles(_) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
307         when: 'the searches api is invoked'
308             def response = mvc.perform(post(searchesEndpoint)
309                 .contentType(MediaType.APPLICATION_JSON)
310                 .content(jsonString)).andReturn().response
311         then: 'cm handle ids are returned'
312             response.contentAsString == '["some-cmhandle-id1","some-cmhandle-id2"]'
313     }
314
315     def 'Query for cm handles with invalid request payload'() {
316         when: 'the searches api is invoked'
317             def searchesEndpoint = "$ncmpBasePathV1/data/ch/searches"
318             def invalidInputData = '{invalidJson}'
319             def response = mvc.perform(post(searchesEndpoint)
320                     .contentType(MediaType.APPLICATION_JSON)
321                     .content(invalidInputData)).andReturn().response
322         then: 'BAD_REQUEST is returned'
323             response.getStatus() == 400
324     }
325
326     def 'Patch resource data in pass-through running datastore.' () {
327         given: 'patch resource data url'
328             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
329                     "?resourceIdentifier=parent/child"
330         when: 'patch data resource request is performed'
331             def response = mvc.perform(
332                     patch(url)
333                             .contentType(MediaType.APPLICATION_JSON)
334                             .accept(MediaType.APPLICATION_JSON).content(requestBody)
335             ).andReturn().response
336         then: 'ncmp service method to update resource is called'
337             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
338                     'parent/child', PATCH, requestBody, 'application/json;charset=UTF-8')
339         and: 'the response status is OK'
340             response.status == HttpStatus.OK.value()
341     }
342
343     def 'Delete resource data in pass-through running datastore.' () {
344         given: 'delete resource data url'
345             def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
346                      "?resourceIdentifier=parent/child"
347         when: 'delete data resource request is performed'
348             def response = mvc.perform(
349                 delete(url).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn().response
350         then: 'the ncmp service method to delete resource is called (with null as body)'
351             1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
352                 'parent/child', DELETE, null, 'application/json;charset=UTF-8')
353         and: 'the response is No Content'
354             response.status == HttpStatus.NO_CONTENT.value()
355     }
356
357     def 'Get resource data from DMI with valid topic i.e. async request for #scenario'() {
358         given: 'resource data url'
359             def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
360                     "?resourceIdentifier=parent/child&options=(a=1,b=2)&topic=my-topic-name"
361         when: 'get data resource request is performed'
362             def response = mvc.perform(
363                     get(getUrl)
364                             .contentType(MediaType.APPLICATION_JSON)
365                             .accept(MediaType.APPLICATION_JSON_VALUE)
366             ).andReturn().response
367         then: 'async request id is generated'
368             assert response.contentAsString.contains("requestId")
369         where: 'the following parameters are used'
370             scenario                   | datastoreInUrl
371             ':passthrough-operational' | 'passthrough-operational'
372             ':passthrough-running'     | 'passthrough-running'
373     }
374
375     def dataStores() {
376         DataStores.builder()
377             .operationalDataStore(Operational.builder()
378                 .syncState('NONE_REQUESTED')
379                 .lastSyncTime(formattedDateAndTime.toString()).build()).build()
380     }
381
382 }
383