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
12 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.cps.ncmp.rest.controller
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.inventory.SyncState
30 import org.onap.cps.ncmp.api.inventory.LockReasonCategory
31 import org.onap.cps.ncmp.api.models.NcmpServiceCmHandle
32 import org.onap.cps.ncmp.rest.mapper.CmHandleStateMapper
33 import org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor
34 import org.onap.cps.ncmp.rest.util.DeprecationHelper
35 import spock.lang.Shared
37 import java.time.OffsetDateTime
38 import java.time.ZoneOffset
39 import java.time.format.DateTimeFormatter
41 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.PATCH
42 import static org.onap.cps.ncmp.api.inventory.CompositeState.DataStores
43 import static org.onap.cps.ncmp.api.inventory.CompositeState.Operational
44 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
45 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
46 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.patch
47 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
48 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
49 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.CREATE
50 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.UPDATE
51 import static org.onap.cps.ncmp.api.impl.operations.DmiRequestBody.OperationEnum.DELETE
53 import com.fasterxml.jackson.databind.ObjectMapper
54 import org.onap.cps.TestUtils
55 import org.onap.cps.spi.model.ModuleReference
56 import org.onap.cps.utils.JsonObjectMapper
57 import org.onap.cps.ncmp.api.NetworkCmProxyDataService
58 import org.spockframework.spring.SpringBean
59 import org.springframework.beans.factory.annotation.Autowired
60 import org.springframework.beans.factory.annotation.Value
61 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
62 import org.springframework.http.HttpStatus
63 import org.springframework.http.MediaType
64 import org.springframework.test.web.servlet.MockMvc
65 import spock.lang.Specification
67 @WebMvcTest(NetworkCmProxyController)
68 class NetworkCmProxyControllerSpec extends Specification {
74 NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
77 ObjectMapper objectMapper = new ObjectMapper()
80 JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(objectMapper)
83 NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
86 CmHandleStateMapper cmHandleStateMapper = Mappers.getMapper(CmHandleStateMapper)
89 CpsNcmpTaskExecutor spiedCpsTaskExecutor = Spy()
92 DeprecationHelper stubbedDeprecationHelper = Stub()
94 @Value('${rest.api.ncmp-base-path}/v1')
97 def requestBody = '{"some-key":"some-value"}'
101 def NO_REQUEST_ID = null
103 def formattedDateAndTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
104 .format(OffsetDateTime.of(2022, 12, 31, 20, 30, 40, 1, ZoneOffset.UTC))
106 def 'Get Resource Data from pass-through operational.'() {
107 given: 'resource data url'
108 def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-operational" +
109 "?resourceIdentifier=parent/child&options=(a=1,b=2)"
110 when: 'get data resource request is performed'
111 def response = mvc.perform(
113 .contentType(MediaType.APPLICATION_JSON)
114 ).andReturn().response
115 then: 'the NCMP data service is called with getResourceDataOperationalForCmHandle'
116 1 * mockNetworkCmProxyDataService.getResourceDataOperationalForCmHandle('testCmHandle',
121 and: 'response status is Ok'
122 response.status == HttpStatus.OK.value()
125 def 'Get Resource Data from #datastoreInUrl with #scenario.'() {
126 given: 'resource data url'
127 def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
128 "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
129 when: 'get data resource request is performed'
130 def response = mvc.perform(
131 get(getUrl).contentType(MediaType.APPLICATION_JSON)).andReturn().response
132 then: 'task executor is called appropriate number of times'
133 expectedNumberOfExecutorExecutions * spiedCpsTaskExecutor.executeTask(_, 2000)
134 and: 'response status is expected'
135 response.status == HttpStatus.OK.value()
136 where: 'the following parameters are used'
137 scenario | datastoreInUrl | topicQueryParam || expectedTopicName | expectedNumberOfExecutorExecutions
138 'url with valid topic' | 'passthrough-operational' | '&topic=my-topic-name' || 'my-topic-name' | 1
139 'no topic in url' | 'passthrough-operational' | '' || NO_TOPIC | 0
140 'null topic in url' | 'passthrough-operational' | '&topic=null' || 'null' | 1
141 'url with valid topic' | 'passthrough-running' | '&topic=my-topic-name' || 'my-topic-name' | 1
142 'no topic in url' | 'passthrough-running' | '' || NO_TOPIC | 0
143 'null topic in url' | 'passthrough-running' | '&topic=null' || 'null' | 1
146 def 'Fail to get Resource Data from #datastoreInUrl when #scenario.'() {
147 given: 'resource data url'
148 def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
149 "?resourceIdentifier=parent/child&options=(a=1,b=2)${topicQueryParam}"
150 when: 'get data resource request is performed'
151 def response = mvc.perform(
152 get(getUrl).contentType(MediaType.APPLICATION_JSON)).andReturn().response
153 then: 'abad request is returned'
154 response.status == HttpStatus.BAD_REQUEST.value()
155 where: 'the following parameters are used'
156 scenario | datastoreInUrl | topicQueryParam
157 'empty topic in url' | 'passthrough-operational' | '&topic=\"\"'
158 'missing topic in url' | 'passthrough-operational' | '&topic='
159 'blank topic value in url' | 'passthrough-operational' | '&topic=\" \"'
160 'invalid non-empty topic value in url' | 'passthrough-operational' | '&topic=1_5_*_#'
161 'empty topic in url' | 'passthrough-running' | '&topic=\"\"'
162 'missing topic in url' | 'passthrough-running' | '&topic='
163 'blank topic value in url' | 'passthrough-running' | '&topic=\" \"'
164 'invalid non-empty topic value in url' | 'passthrough-running' | '&topic=1_5_*_#'
167 def 'Get Resource Data from pass-through running with #scenario value in resource identifier param.'() {
168 given: 'resource data url'
169 def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
170 "?resourceIdentifier=" + resourceIdentifier + "&options=(a=1,b=2)"
171 and: 'ncmp service returns json object'
172 mockNetworkCmProxyDataService.getResourceDataPassThroughRunningForCmHandle('testCmHandle',
176 NO_REQUEST_ID) >> '{valid-json}'
177 when: 'get data resource request is performed'
178 def response = mvc.perform(
180 .contentType(MediaType.APPLICATION_JSON)
181 ).andReturn().response
182 then: 'response status is Ok'
183 response.status == HttpStatus.OK.value()
184 and: 'response contains valid object body'
185 response.getContentAsString() == '{valid-json}'
186 where: 'tokens are used in the resource identifier parameter'
187 scenario | resourceIdentifier
188 '/' | 'id/with/slashes'
193 '? needs to be encoded as %3F' | 'idWith%3F'
196 def 'Update resource data from pass-through running.' () {
197 given: 'update resource data url'
198 def updateUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
199 "?resourceIdentifier=parent/child"
200 when: 'update data resource request is performed'
201 def response = mvc.perform(
203 .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
204 ).andReturn().response
205 then: 'ncmp service method to update resource is called'
206 1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
207 'parent/child', UPDATE, requestBody, 'application/json;charset=UTF-8')
208 and: 'the response status is OK'
209 response.status == HttpStatus.OK.value()
212 def 'Create Resource Data from pass-through running with #scenario.' () {
213 given: 'resource data url'
214 def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
215 "?resourceIdentifier=parent/child"
216 def requestBody = '{"some-key":"some-value"}'
217 when: 'create resource request is performed'
218 def response = mvc.perform(
220 .contentType(MediaType.APPLICATION_JSON_VALUE).content(requestBody)
221 ).andReturn().response
222 then: 'ncmp service method to create resource called'
223 1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
224 'parent/child', CREATE, requestBody, 'application/json;charset=UTF-8')
225 and: 'resource is created'
226 response.status == HttpStatus.CREATED.value()
229 def 'Get module references for the given dataspace and cm handle.' () {
230 given: 'get module references url'
231 def getUrl = "$ncmpBasePathV1/ch/some-cmhandle/modules"
232 when: 'get module resource request is performed'
233 def response =mvc.perform(get(getUrl)).andReturn().response
234 then: 'ncmp service method to get yang resource module references is called'
235 mockNetworkCmProxyDataService.getYangResourcesModuleReferences('some-cmhandle')
236 >> [new ModuleReference(moduleName: 'some-name1',revision: '2021-10-03')]
237 and: 'response contains an array with the module name and revision'
238 response.getContentAsString() == '[{"moduleName":"some-name1","revision":"2021-10-03"}]'
239 and: 'response returns an OK http code'
240 response.status == HttpStatus.OK.value()
243 def 'Retrieve cm handles.'() {
244 given: 'an endpoint and json data'
245 def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
246 String jsonString = TestUtils.getResourceFileContent('cmhandle-search.json')
247 and: 'the service method is invoked with module names and returns two cm handles'
248 def cmHandle1 = new NcmpServiceCmHandle()
249 cmHandle1.cmHandleId = 'some-cmhandle-id1'
250 cmHandle1.publicProperties = [color:'yellow']
251 def cmHandle2 = new NcmpServiceCmHandle()
252 cmHandle2.cmHandleId = 'some-cmhandle-id2'
253 cmHandle2.publicProperties = [color:'green']
254 mockNetworkCmProxyDataService.executeCmHandleSearch(_) >> [cmHandle1, cmHandle2]
255 when: 'the searches api is invoked'
256 def response = mvc.perform(post(searchesEndpoint)
257 .contentType(MediaType.APPLICATION_JSON)
258 .content(jsonString)).andReturn().response
259 then: 'response status returns OK'
260 response.status == HttpStatus.OK.value()
261 and: 'the expected response content is returned'
262 response.contentAsString == '[{"cmHandle":"some-cmhandle-id1","publicCmHandleProperties":[{"color":"yellow"}],"state":null},{"cmHandle":"some-cmhandle-id2","publicCmHandleProperties":[{"color":"green"}],"state":null}]'
265 def 'Get complete Cm Handle details by Cm Handle id.'() {
266 given: 'an endpoint and a cm handle'
267 def cmHandleDetailsEndpoint = "$ncmpBasePathV1/ch/some-cm-handle"
268 and: 'an existing ncmp service cm handle'
269 def cmHandleId = 'some-cm-handle'
270 def dmiProperties = [ prop:'some DMI property' ]
271 def publicProperties = [ "public prop":'some public property' ]
272 def compositeState = compositeStateTestObject()
273 def ncmpServiceCmHandle = new NcmpServiceCmHandle(cmHandleId: cmHandleId, dmiProperties: dmiProperties, publicProperties: publicProperties, compositeState: compositeState)
274 and: 'the service method is invoked with the cm handle id'
275 1 * mockNetworkCmProxyDataService.getNcmpServiceCmHandle('some-cm-handle') >> ncmpServiceCmHandle
276 when: 'the cm handle details api is invoked'
277 def response = mvc.perform(get(cmHandleDetailsEndpoint)).andReturn().response
278 then: 'the correct response is returned'
279 response.status == HttpStatus.OK.value()
280 and: 'the response contains the public properties'
281 assertContainsPublicProperties(response)
282 and: 'the response contains the cm handle state'
283 assertContainsState(response)
284 and: 'the content does not contain dmi properties'
285 !response.contentAsString.contains("some DMI property")
288 def 'Get Cm Handle public properties by Cm Handle id.' () {
289 given: 'a cm handle properties endpoint'
290 def cmHandlePropertiesEndpoint = "$ncmpBasePathV1/ch/some-cm-handle/properties"
291 and: 'some cm handle public properties'
292 def publicProperties = [ 'public prop':'some public property' ]
293 and: 'the service method is invoked with the cm handle id returning the cm handle public properties'
294 1 * mockNetworkCmProxyDataService.getCmHandlePublicProperties('some-cm-handle') >> publicProperties
295 when: 'the cm handle properties api is invoked'
296 def response = mvc.perform(get(cmHandlePropertiesEndpoint)).andReturn().response
297 then: 'the correct response is returned'
298 response.status == HttpStatus.OK.value()
299 and: 'the response contains the public properties'
300 assertContainsPublicProperties(response)
303 def 'Get Cm Handle composite state by Cm Handle id.' () {
304 given: 'a cm handle state endpoint'
305 def cmHandlePropertiesEndpoint = "$ncmpBasePathV1/ch/some-cm-handle/state"
306 and: 'some cm handle composite state'
307 def compositeState = compositeStateTestObject()
308 and: 'the service method is invoked with the cm handle id returning the cm handle composite state'
309 1 * mockNetworkCmProxyDataService.getCmHandleCompositeState('some-cm-handle') >> compositeState
310 when: 'the cm handle state api is invoked'
311 def response = mvc.perform(get(cmHandlePropertiesEndpoint)).andReturn().response
312 then: 'the correct response is returned'
313 response.status == HttpStatus.OK.value()
314 and: 'the response contains the cm handle state'
315 assertContainsState(response)
318 def 'Call execute cm handle searches with unrecognized condition name.'() {
319 given: 'an endpoint and json data'
320 def searchesEndpoint = "$ncmpBasePathV1/ch/searches"
321 String jsonString = TestUtils.getResourceFileContent('invalid-cmhandle-search.json')
322 and: 'the service method is invoked with module names and returns two cm handles'
323 def cmHandel1 = new NcmpServiceCmHandle()
324 cmHandel1.cmHandleId = 'some-cmhandle-id1'
325 cmHandel1.publicProperties = [color:'yellow']
326 def cmHandel2 = new NcmpServiceCmHandle()
327 cmHandel2.cmHandleId = 'some-cmhandle-id2'
328 cmHandel2.publicProperties = [color:'green']
329 mockNetworkCmProxyDataService.executeCmHandleSearch(_) >> [cmHandel1, cmHandel2]
330 when: 'the searches api is invoked'
331 def response = mvc.perform(post(searchesEndpoint)
332 .contentType(MediaType.APPLICATION_JSON)
333 .content(jsonString)).andReturn().response
334 then: 'an empty cm handle identifier is returned'
335 response.contentAsString == '[{"cmHandle":"some-cmhandle-id1","publicCmHandleProperties":[{"color":"yellow"}],"state":null},{"cmHandle":"some-cmhandle-id2","publicCmHandleProperties":[{"color":"green"}],"state":null}]'
338 def 'Query for cm handles matching query parameters'() {
339 given: 'an endpoint and json data'
340 def searchesEndpoint = "$ncmpBasePathV1/ch/id-searches"
341 and: 'the service method is invoked with module names and returns cm handle ids'
342 1 * mockNetworkCmProxyDataService.executeCmHandleIdSearch(_) >> ['some-cmhandle-id1', 'some-cmhandle-id2']
343 when: 'the searches api is invoked'
344 def response = mvc.perform(post(searchesEndpoint)
345 .contentType(MediaType.APPLICATION_JSON)
346 .content('{}')).andReturn().response
347 then: 'cm handle ids are returned'
348 response.contentAsString == '["some-cmhandle-id1","some-cmhandle-id2"]'
351 def 'Query for cm handles with invalid request payload'() {
352 when: 'the searches api is invoked'
353 def searchesEndpoint = "$ncmpBasePathV1/ch/id-searches"
354 def invalidInputData = '{invalidJson}'
355 def response = mvc.perform(post(searchesEndpoint)
356 .contentType(MediaType.APPLICATION_JSON)
357 .content(invalidInputData)).andReturn().response
358 then: 'BAD_REQUEST is returned'
359 response.getStatus() == 400
362 def 'Patch resource data in pass-through running datastore.' () {
363 given: 'patch resource data url'
364 def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
365 "?resourceIdentifier=parent/child"
366 when: 'patch data resource request is performed'
367 def response = mvc.perform(
369 .contentType(MediaType.APPLICATION_JSON)
370 .accept(MediaType.APPLICATION_JSON).content(requestBody)
371 ).andReturn().response
372 then: 'ncmp service method to update resource is called'
373 1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
374 'parent/child', PATCH, requestBody, 'application/json;charset=UTF-8')
375 and: 'the response status is OK'
376 response.status == HttpStatus.OK.value()
379 def 'Delete resource data in pass-through running datastore.' () {
380 given: 'delete resource data url'
381 def url = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:passthrough-running" +
382 "?resourceIdentifier=parent/child"
383 when: 'delete data resource request is performed'
384 def response = mvc.perform(
385 delete(url).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andReturn().response
386 then: 'the ncmp service method to delete resource is called (with null as body)'
387 1 * mockNetworkCmProxyDataService.writeResourceDataPassThroughRunningForCmHandle('testCmHandle',
388 'parent/child', DELETE, null, 'application/json;charset=UTF-8')
389 and: 'the response is No Content'
390 response.status == HttpStatus.NO_CONTENT.value()
393 def 'Get resource data from DMI with valid topic i.e. async request for #scenario'() {
394 given: 'resource data url'
395 def getUrl = "$ncmpBasePathV1/ch/testCmHandle/data/ds/ncmp-datastore:${datastoreInUrl}" +
396 "?resourceIdentifier=parent/child&options=(a=1,b=2)&topic=my-topic-name"
397 when: 'get data resource request is performed'
398 def response = mvc.perform(
400 .contentType(MediaType.APPLICATION_JSON)
401 .accept(MediaType.APPLICATION_JSON_VALUE)
402 ).andReturn().response
403 then: 'async request id is generated'
404 assert response.contentAsString.contains("requestId")
405 where: 'the following parameters are used'
406 scenario | datastoreInUrl
407 ':passthrough-operational' | 'passthrough-operational'
408 ':passthrough-running' | 'passthrough-running'
413 .operationalDataStore(Operational.builder()
414 .syncState(SyncState.NONE_REQUESTED)
415 .lastSyncTime(formattedDateAndTime.toString()).build()).build()
418 def compositeStateTestObject() {
419 new CompositeState(cmHandleState: CmHandleState.ADVISED,
420 lockReason: CompositeState.LockReason.builder().lockReasonCategory(LockReasonCategory.LOCKED_MISBEHAVING).details("lock misbehaving details").build(),
421 lastUpdateTime: formattedDateAndTime.toString(),
422 dataSyncEnabled: false,
423 dataStores: dataStores())
426 def assertContainsAll(response, assertContent) {
427 assertContent.forEach( string -> { assert(response.contentAsString.contains(string)) })
431 def assertContainsState(response) {
432 def expectedContent = [
434 '"cmHandleState":"ADVISED"',
435 '"reason":"LOCKED_MISBEHAVING"',
436 '"details":"lock misbehaving details"',
437 '"lastUpdateTime":"2022-12-31T20:30:40.000+0000"',
438 '"dataSyncEnabled":false',
441 '"state":"NONE_REQUESTED"',
442 '"lastSyncTime":"2022-12-31T20:30:40.000+0000"',
445 return assertContainsAll(response, expectedContent)
448 def assertContainsPublicProperties(response) {
449 def expectedContent = [
450 '"publicCmHandleProperties":' ,
452 '"some public property"'
454 return assertContainsAll(response, expectedContent)