2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2020-2021 Pantheon.tech
4 * Modifications Copyright (C) 2020-2021 Bell Canada.
5 * Modifications Copyright (C) 2021-2025 Nordix Foundation
6 * Modifications Copyright (C) 2022-2025 TechMahindra Ltd.
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.rest.controller
26 import com.fasterxml.jackson.databind.ObjectMapper
28 import static org.onap.cps.api.parameters.CascadeDeleteAllowed.CASCADE_DELETE_PROHIBITED
29 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
30 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
31 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart
32 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
33 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put
35 import org.mapstruct.factory.Mappers
36 import org.onap.cps.api.CpsAnchorService
37 import org.onap.cps.api.CpsDataspaceService
38 import org.onap.cps.api.CpsModuleService
39 import org.onap.cps.api.CpsNotificationService
40 import org.onap.cps.api.exceptions.AlreadyDefinedException
41 import org.onap.cps.api.exceptions.SchemaSetInUseException
42 import org.onap.cps.api.model.Anchor
43 import org.onap.cps.api.model.Dataspace
44 import org.onap.cps.api.model.SchemaSet
45 import org.onap.cps.utils.JsonObjectMapper
46 import org.spockframework.spring.SpringBean
47 import org.springframework.beans.factory.annotation.Autowired
48 import org.springframework.beans.factory.annotation.Value
49 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
50 import org.springframework.http.HttpStatus
51 import org.springframework.http.MediaType
52 import org.springframework.mock.web.MockMultipartFile
53 import org.springframework.test.web.servlet.MockMvc
54 import org.springframework.util.LinkedMultiValueMap
55 import org.springframework.util.MultiValueMap
56 import spock.lang.Specification
58 import static org.onap.cps.api.parameters.CascadeDeleteAllowed.CASCADE_DELETE_PROHIBITED
59 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
60 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
61 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart
62 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
64 @WebMvcTest(AdminRestController)
65 class AdminRestControllerSpec extends Specification {
68 CpsModuleService mockCpsModuleService = Mock()
71 CpsDataspaceService mockCpsDataspaceService = Mock()
74 CpsAnchorService mockCpsAnchorService = Mock()
77 CpsNotificationService mockCpsNotificationService = Mock()
80 CpsRestInputMapper cpsRestInputMapper = Mappers.getMapper(CpsRestInputMapper)
83 JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
89 @Value('${rest.api.cps-base-path}')
92 def dataspaceName = 'my_dataspace'
93 def anchorName = 'my_anchor'
94 def schemaSetName = 'my_schema_set'
95 def anchor = new Anchor(name: anchorName, dataspaceName: dataspaceName, schemaSetName: schemaSetName)
96 def dataspace = new Dataspace(name: dataspaceName)
98 def 'Create new dataspace with #scenario.'() {
99 when: 'post is invoked on endpoint for creating a dataspace'
102 post("/cps/api/${apiVersion}/dataspaces")
103 .param('dataspace-name', dataspaceName))
104 .andReturn().response
105 then: 'service method is invoked with expected parameters'
106 1 * mockCpsDataspaceService.createDataspace(dataspaceName)
107 and: 'dataspace is create successfully'
108 response.status == HttpStatus.CREATED.value()
109 assert response.getContentAsString() == expectedResponseBody
110 where: 'following cases are tested'
111 scenario | apiVersion || expectedResponseBody
112 'V1 API' | 'v1' || 'my_dataspace'
113 'V2 API' | 'v2' || ''
116 def 'Create dataspace over existing with same name.'() {
117 given: 'the endpoint to create a dataspace'
118 def createDataspaceEndpoint = "$basePath/v1/dataspaces"
119 and: 'the service method throws an exception indicating the dataspace is already defined'
120 def thrownException = new AlreadyDefinedException(dataspaceName, new RuntimeException())
121 mockCpsDataspaceService.createDataspace(dataspaceName) >> { throw thrownException }
122 when: 'post is invoked'
125 post(createDataspaceEndpoint)
126 .param('dataspace-name', dataspaceName))
127 .andReturn().response
128 then: 'dataspace creation fails'
129 response.status == HttpStatus.CONFLICT.value()
132 def 'Get a dataspace.'() {
133 given: 'service method returns a dataspace'
134 mockCpsDataspaceService.getDataspace(dataspaceName) >> dataspace
135 and: 'the endpoint for getting a dataspace by name'
136 def getDataspaceEndpoint = "$basePath/v1/admin/dataspaces/$dataspaceName"
137 when: 'get dataspace API is invoked'
138 def response = mvc.perform(get(getDataspaceEndpoint)).andReturn().response
139 then: 'the correct dataspace is returned'
140 response.status == HttpStatus.OK.value()
141 response.getContentAsString().contains(dataspaceName)
144 def 'Clean a dataspace.'() {
145 given: 'service method returns a dataspace'
146 mockCpsDataspaceService.getDataspace(dataspaceName) >> dataspace
147 and: 'the endpoint for cleaning a dataspace'
148 def postCleanDataspaceEndpoint = "$basePath/v1/admin/dataspaces/$dataspaceName/actions/clean"
149 when: 'post is invoked on the clean dataspace endpoint'
150 def response = mvc.perform(post(postCleanDataspaceEndpoint)).andReturn().response
151 then: 'no content is returned'
152 response.status == HttpStatus.NO_CONTENT.value()
155 def 'Get all dataspaces.'() {
156 given: 'service method returns all dataspace'
157 mockCpsDataspaceService.getAllDataspaces() >> [dataspace, new Dataspace(name: "dataspace-test2")]
159 def getAllDataspaceEndpoint = "$basePath/v1/admin/dataspaces"
160 when: 'get all dataspace API is invoked'
161 def response = mvc.perform(get(getAllDataspaceEndpoint)).andReturn().response
162 then: 'the correct dataspace is returned'
163 response.status == HttpStatus.OK.value()
164 response.getContentAsString().contains(dataspaceName)
165 response.getContentAsString().contains("dataspace-test2")
168 def 'Create schema set from yang file with #scenario.'() {
169 def yangResourceMapCapture
170 given: 'single yang file'
171 def multipartFile = createMultipartFile("filename.yang", "content")
172 when: 'file uploaded with schema set create request'
175 multipart("/cps/api/${apiVersion}/dataspaces/my_dataspace/schema-sets")
177 .param('schema-set-name', schemaSetName))
178 .andReturn().response
179 then: 'associated service method is invoked with expected parameters'
180 1 * mockCpsModuleService.createSchemaSet(dataspaceName, schemaSetName, _) >>
181 { args -> yangResourceMapCapture = args[2] }
182 yangResourceMapCapture['filename.yang'] == 'content'
183 and: 'response code indicates success'
184 assert response.status == HttpStatus.CREATED.value()
185 assert response.getContentAsString() == expectedResponseBody
186 where: 'following cases are tested'
187 scenario | apiVersion || expectedResponseBody
188 'V1 API' | 'v1' || 'my_schema_set'
189 'V2 API' | 'v2' || ''
192 def 'Create schema set from zip archive with #scenario.'() {
193 def yangResourceMapCapture
194 given: 'zip archive with multiple .yang files inside'
195 def multipartFile = createZipMultipartFileFromResource("/yang-files-set.zip")
196 when: 'file uploaded with schema set create request'
199 multipart("/cps/api/${apiVersion}/dataspaces/my_dataspace/schema-sets")
201 .param('schema-set-name', schemaSetName))
202 .andReturn().response
203 then: 'associated service method is invoked with expected parameters'
204 1 * mockCpsModuleService.createSchemaSet(dataspaceName, schemaSetName, _) >> { args -> yangResourceMapCapture = args[2] }
205 yangResourceMapCapture['assembly.yang'] == "fake assembly content 1\n"
206 yangResourceMapCapture['component.yang'] == "fake component content 1\n"
207 and: 'response code indicates success'
208 assert response.status == HttpStatus.CREATED.value()
209 assert response.getContentAsString() == expectedResponseBody
210 where: 'following cases are tested'
211 scenario | apiVersion || expectedResponseBody
212 'V1 API' | 'v1' || 'my_schema_set'
213 'V2 API' | 'v2' || ''
216 def 'Create a schema set from a yang file that is greater than 1MB #scenario.'() {
217 given: 'a yang file greater than 1MB'
218 def multipartFile = createMultipartFileFromResource("/model-over-1mb.yang")
219 when: 'a file is uploaded to the create schema set endpoint'
222 multipart("/cps/api/${apiVersion}/dataspaces/my_dataspace/schema-sets")
224 .param('schema-set-name', schemaSetName))
225 .andReturn().response
226 then: 'the associated service method is invoked'
227 1 * mockCpsModuleService.createSchemaSet(dataspaceName, schemaSetName, _)
228 and: 'the response code indicates success'
229 assert response.status == HttpStatus.CREATED.value()
230 assert response.getContentAsString() == expectedResponseBody
231 where: 'following cases are tested'
232 scenario | apiVersion || expectedResponseBody
233 'V1 API' | 'v1' || 'my_schema_set'
234 'V2 API' | 'v2' || ''
237 def 'Create schema set from zip archive having #caseDescriptor.'() {
238 given: 'the endpoint to create a schema set'
239 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
240 when: 'zip archive having #caseDescriptor is uploaded with create schema set request'
243 multipart(schemaSetEndpoint)
245 .param('schema-set-name', schemaSetName))
246 .andReturn().response
247 then: 'create schema set rejected'
248 response.status == HttpStatus.BAD_REQUEST.value()
249 where: 'following cases are tested'
250 caseDescriptor | multipartFile
251 'no .yang files inside' | createZipMultipartFileFromResource("/no-yang-files.zip")
252 'multiple .yang files with same name' | createZipMultipartFileFromResource("/yang-files-multiple-sets.zip")
255 def 'Create schema set from file with unsupported filename extension.'() {
256 given: 'file with unsupported filename extension (.doc)'
257 def multipartFile = createMultipartFile("filename.doc", "content")
258 and: 'the endpoint to create a schema set'
259 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
260 when: 'file uploaded with schema set create request'
263 multipart(schemaSetEndpoint)
265 .param('schema-set-name', schemaSetName))
266 .andReturn().response
267 then: 'create schema set rejected'
268 response.status == HttpStatus.BAD_REQUEST.value()
271 def 'Create schema set from #fileType file with IOException occurrence on processing.'() {
272 given: 'the endpoint to create a schema set'
273 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
274 when: 'file uploaded with schema set create request'
275 def multipartFile = createMultipartFileForIOException(fileType)
278 multipart(schemaSetEndpoint)
280 .param('schema-set-name', schemaSetName))
281 .andReturn().response
282 then: 'the error response returned indicating internal server error occurrence'
283 response.status == HttpStatus.INTERNAL_SERVER_ERROR.value()
284 where: 'following file types are used'
285 fileType << ['YANG', 'ZIP']
288 def 'Delete schema set.'() {
289 given: 'the endpoint for deleting a schema set'
290 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets/$schemaSetName"
291 when: 'delete schema set endpoint is invoked'
292 def response = mvc.perform(delete(schemaSetEndpoint)).andReturn().response
293 then: 'associated service method is invoked with expected parameters'
294 1 * mockCpsModuleService.deleteSchemaSet(dataspaceName, schemaSetName, CASCADE_DELETE_PROHIBITED)
295 and: 'response code indicates success'
296 response.status == HttpStatus.NO_CONTENT.value()
299 def 'Delete schema set which is in use.'() {
300 given: 'service method throws an exception indicating the schema set is in use'
301 def thrownException = new SchemaSetInUseException(dataspaceName, schemaSetName)
302 mockCpsModuleService.deleteSchemaSet(dataspaceName, schemaSetName, CASCADE_DELETE_PROHIBITED) >>
303 { throw thrownException }
304 and: 'the endpoint for deleting a schema set'
305 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets/$schemaSetName"
306 when: 'delete schema set endpoint is invoked'
307 def response = mvc.perform(delete(schemaSetEndpoint)).andReturn().response
308 then: 'schema set deletion fails with conflict response code'
309 response.status == HttpStatus.CONFLICT.value()
312 def 'Get existing schema set.'() {
313 given: 'service method returns a new schema set'
314 mockCpsModuleService.getSchemaSet(dataspaceName, schemaSetName) >>
315 new SchemaSet(name: schemaSetName, dataspaceName: dataspaceName)
316 and: 'the endpoint for getting a schema set'
317 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets/$schemaSetName"
318 when: 'get schema set API is invoked'
319 def response = mvc.perform(get(schemaSetEndpoint)).andReturn().response
320 then: 'the correct schema set is returned'
321 response.status == HttpStatus.OK.value()
322 response.getContentAsString().contains(schemaSetName)
325 def 'Get all schema sets for a given dataspace name.'() {
326 given: 'service method returns all schema sets for a dataspace'
327 mockCpsModuleService.getSchemaSets(dataspaceName) >>
328 [new SchemaSet(name: schemaSetName, dataspaceName: dataspaceName),
329 new SchemaSet(name: "test-schemaset", dataspaceName: dataspaceName)]
330 and: 'the endpoint for getting all schema sets'
331 def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
332 when: 'get schema sets API is invoked'
333 def response = mvc.perform(get(schemaSetEndpoint)).andReturn().response
334 then: 'the correct schema sets is returned'
335 assert response.status == HttpStatus.OK.value()
336 assert response.getContentAsString() == '[{"dataspaceName":"my_dataspace","moduleReferences":[],"name":' +
337 '"my_schema_set"},{"dataspaceName":"my_dataspace","moduleReferences":[],"name":"test-schemaset"}]'
340 def 'Create Anchor with #scenario.'() {
341 given: 'request parameters'
342 def requestParams = new LinkedMultiValueMap<>()
343 requestParams.add('schema-set-name', schemaSetName)
344 requestParams.add('anchor-name', anchorName)
345 when: 'post is invoked on the create anchors endpoint'
348 post("/cps/api/${apiVersion}/dataspaces/my_dataspace/anchors")
349 .contentType(MediaType.APPLICATION_JSON)
350 .params(requestParams as MultiValueMap))
351 .andReturn().response
352 then: 'anchor is created successfully'
353 1 * mockCpsAnchorService.createAnchor(dataspaceName, schemaSetName, anchorName)
354 assert response.status == HttpStatus.CREATED.value()
355 assert response.getContentAsString() == expectedResponseBody
356 where: 'following cases are tested'
357 scenario | apiVersion || expectedResponseBody
358 'V1 API' | 'v1' || 'my_anchor'
359 'V2 API' | 'v2' || ''
362 def 'Get existing anchors.'() {
363 given: 'service method returns a list of (one) anchors'
364 mockCpsAnchorService.getAnchors(dataspaceName) >> [anchor]
365 and: 'the endpoint for getting all anchors'
366 def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors"
367 when: 'get all anchors API is invoked'
368 def response = mvc.perform(get(anchorEndpoint)).andReturn().response
369 then: 'the correct anchor is returned'
370 response.status == HttpStatus.OK.value()
371 response.getContentAsString().contains(anchorName)
374 def 'Get existing anchor by dataspace and anchor name.'() {
375 given: 'service method returns an anchor'
376 mockCpsAnchorService.getAnchor(dataspaceName, anchorName) >>
377 new Anchor(name: anchorName, dataspaceName: dataspaceName, schemaSetName: schemaSetName)
378 and: 'the endpoint for getting an anchor'
379 def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors/$anchorName"
380 when: 'get anchor API is invoked'
381 def response = mvc.perform(get(anchorEndpoint)).andReturn().response
382 def responseContent = response.getContentAsString()
383 then: 'the correct anchor is returned'
384 response.status == HttpStatus.OK.value()
385 responseContent.contains(anchorName)
386 responseContent.contains(dataspaceName)
387 responseContent.contains(schemaSetName)
390 def 'Delete anchor.'() {
391 given: 'the endpoint for deleting an anchor'
392 def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors/$anchorName"
393 when: 'delete method is invoked on anchor endpoint'
394 def response = mvc.perform(delete(anchorEndpoint)).andReturn().response
395 then: 'associated service method is invoked with expected parameters'
396 1 * mockCpsAnchorService.deleteAnchor(dataspaceName, anchorName)
397 and: 'response code indicates success'
398 response.status == HttpStatus.NO_CONTENT.value()
401 def 'Delete dataspace.'() {
402 given: 'the endpoint for deleting a dataspace'
403 def dataspaceEndpoint = "$basePath/v1/dataspaces"
404 when: 'delete dataspace endpoint is invoked'
405 def response = mvc.perform(delete(dataspaceEndpoint)
406 .param('dataspace-name', dataspaceName))
407 .andReturn().response
408 then: 'associated service method is invoked with expected parameter'
409 1 * mockCpsDataspaceService.deleteDataspace(dataspaceName)
410 and: 'response code indicates success'
411 response.status == HttpStatus.NO_CONTENT.value()
414 def 'Add notification subscription'() {
415 given: 'an endpoint and its payload'
416 def notificationSubscriptionEndpoint = "$basePath/v2/notification-subscription"
417 def xpath = '/dataspaces'
418 def jsonPayload = '{"dataspace":[{"name":"ds01"}]}'
419 when: 'post request is performed'
422 post(notificationSubscriptionEndpoint)
423 .contentType(MediaType.APPLICATION_JSON)
424 .content(jsonPayload))
425 .andReturn().response
426 then: 'notification service method is invoked with expected parameter'
427 1 * mockCpsNotificationService.createNotificationSubscription(jsonPayload, xpath)
428 and: 'HTTP response code indicates success'
429 response.status == HttpStatus.CREATED.value()
432 def 'delete notification subscription'() {
433 given: 'an endpoint and xpath'
434 def notificationSubscriptionEndpoint = "$basePath/v2/notification-subscription"
435 def xpath = '/dataspaces'
436 when: 'delete request is performed'
437 def response = mvc.perform(delete(notificationSubscriptionEndpoint).param('xpath', xpath)).andReturn().response
438 then: 'notification service method is invoked with expected parameter'
439 1 * mockCpsNotificationService.deleteNotificationSubscription(xpath)
440 and: 'HTTP response code indicates success'
441 response.status == HttpStatus.NO_CONTENT.value()
444 def 'Get notification subscription.'() {
445 given: 'an endpoint and xpath'
446 def notificationSubscriptionEndpoint = "$basePath/v2/notification-subscription"
447 def xpath = '/dataspaces'
448 when: 'get notification subscription is invoked'
449 def response = mvc.perform(get(notificationSubscriptionEndpoint).param('xpath', xpath)).andReturn().response
450 then: 'HTTP response code indicates success'
451 response.status == HttpStatus.OK.value()
452 and: 'notification service is called with proper parameters'
453 1 * mockCpsNotificationService.getNotificationSubscription(xpath)
456 def createMultipartFile(filename, content) {
457 return new MockMultipartFile("file", filename, "text/plain", content.getBytes())
460 def createZipMultipartFileFromResource(resourcePath) {
461 return new MockMultipartFile("file", "test.zip", "application/zip",
462 getClass().getResource(resourcePath).getBytes())
465 def createMultipartFileFromResource(resourcePath) {
466 return new MockMultipartFile("file", "test.yang", "application/text",
467 getClass().getResource(resourcePath).getBytes())
470 def createMultipartFileForIOException(extension) {
471 def multipartFile = Mock(MockMultipartFile)
472 multipartFile.getOriginalFilename() >> "TEST." + extension
473 multipartFile.getBytes() >> { throw new IOException() }
474 multipartFile.getInputStream() >> { throw new IOException() }