Check preformance impacts
[cps.git] / cps-rest / src / test / groovy / org / onap / cps / rest / controller / AdminRestControllerSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2020-2021 Pantheon.tech
4  *  Modifications Copyright (C) 2020-2021 Bell Canada.
5  *  Modifications Copyright (C) 2021-2022 Nordix Foundation
6  *  Modifications Copyright (C) 2022 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
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.rest.controller
25
26 import static org.onap.cps.spi.CascadeDeleteAllowed.CASCADE_DELETE_PROHIBITED
27 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete
28 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
29 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.multipart
30 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
31
32 import org.mapstruct.factory.Mappers
33 import org.onap.cps.api.CpsAdminService
34 import org.onap.cps.api.CpsModuleService
35 import org.onap.cps.spi.exceptions.AlreadyDefinedException
36 import org.onap.cps.spi.exceptions.SchemaSetInUseException
37 import org.onap.cps.spi.model.Anchor
38 import org.onap.cps.spi.model.Dataspace
39 import org.onap.cps.spi.model.SchemaSet
40 import org.spockframework.spring.SpringBean
41 import org.springframework.beans.factory.annotation.Autowired
42 import org.springframework.beans.factory.annotation.Value
43 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
44 import org.springframework.http.HttpStatus
45 import org.springframework.http.MediaType
46 import org.springframework.mock.web.MockMultipartFile
47 import org.springframework.test.web.servlet.MockMvc
48 import org.springframework.util.LinkedMultiValueMap
49 import org.springframework.util.MultiValueMap
50 import spock.lang.Specification
51
52 @WebMvcTest(AdminRestController)
53 class AdminRestControllerSpec extends Specification {
54
55     @SpringBean
56     CpsModuleService mockCpsModuleService = Mock()
57
58     @SpringBean
59     CpsAdminService mockCpsAdminService = Mock()
60
61     @SpringBean
62     CpsRestInputMapper cpsRestInputMapper = Mappers.getMapper(CpsRestInputMapper)
63
64     @Autowired
65     MockMvc mvc
66
67     @Value('${rest.api.cps-base-path}')
68     def basePath
69
70     def dataspaceName = 'my_dataspace'
71     def anchorName = 'my_anchor'
72     def schemaSetName = 'my_schema_set'
73     def anchor = new Anchor(name: anchorName, dataspaceName: dataspaceName, schemaSetName: schemaSetName)
74     def dataspace = new Dataspace(name: dataspaceName)
75
76     def 'Create new dataspace.'() {
77         given: 'an endpoint'
78             def createDataspaceEndpoint = "$basePath/v1/dataspaces"
79         when: 'post is invoked'
80             def response =
81                     mvc.perform(
82                             post(createDataspaceEndpoint)
83                                     .param('dataspace-name', dataspaceName))
84                             .andReturn().response
85         then: 'service method is invoked with expected parameters'
86             1 * mockCpsAdminService.createDataspace(dataspaceName)
87         and: 'dataspace is create successfully'
88             response.status == HttpStatus.CREATED.value()
89     }
90
91     def 'Create dataspace over existing with same name.'() {
92         given: 'an endpoint'
93             def createDataspaceEndpoint = "$basePath/v1/dataspaces"
94         and: 'the service method throws an exception indicating the dataspace is already defined'
95             def thrownException = new AlreadyDefinedException(dataspaceName, new RuntimeException())
96             mockCpsAdminService.createDataspace(dataspaceName) >> { throw thrownException }
97         when: 'post is invoked'
98             def response =
99                     mvc.perform(
100                             post(createDataspaceEndpoint)
101                                     .param('dataspace-name', dataspaceName))
102                             .andReturn().response
103         then: 'dataspace creation fails'
104             response.status == HttpStatus.CONFLICT.value()
105     }
106
107     def 'Get a dataspace.'() {
108         given: 'service method returns a dataspace'
109             mockCpsAdminService.getDataspace(dataspaceName) >> dataspace
110         and: 'an endpoint'
111             def getDataspaceEndpoint = "$basePath/v1/admin/dataspaces/$dataspaceName"
112         when: 'get dataspace API is invoked'
113             def response = mvc.perform(get(getDataspaceEndpoint)).andReturn().response
114         then: 'the correct dataspace is returned'
115             response.status == HttpStatus.OK.value()
116             response.getContentAsString().contains(dataspaceName)
117     }
118
119     def 'Get all dataspaces.'() {
120         given: 'service method returns all dataspace'
121             mockCpsAdminService.getAllDataspaces() >> [dataspace, new Dataspace(name: "dataspace-test2")]
122         and: 'an endpoint'
123             def getAllDataspaceEndpoint = "$basePath/v1/admin/dataspaces"
124         when: 'get all dataspace API is invoked'
125             def response = mvc.perform(get(getAllDataspaceEndpoint)).andReturn().response
126         then: 'the correct dataspace is returned'
127             response.status == HttpStatus.OK.value()
128             response.getContentAsString().contains(dataspaceName)
129             response.getContentAsString().contains("dataspace-test2")
130     }
131
132     def 'Create schema set from yang file.'() {
133         def yangResourceMapCapture
134         given: 'single yang file'
135             def multipartFile = createMultipartFile("filename.yang", "content")
136         and: 'an endpoint'
137             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
138         when: 'file uploaded with schema set create request'
139             def response =
140                     mvc.perform(
141                             multipart(schemaSetEndpoint)
142                                     .file(multipartFile)
143                                     .param('schema-set-name', schemaSetName))
144                             .andReturn().response
145         then: 'associated service method is invoked with expected parameters'
146             1 * mockCpsModuleService.createSchemaSet(dataspaceName, schemaSetName, _) >>
147                     { args -> yangResourceMapCapture = args[2] }
148             yangResourceMapCapture['filename.yang'] == 'content'
149         and: 'response code indicates success'
150             response.status == HttpStatus.CREATED.value()
151     }
152
153     def 'Create schema set from zip archive.'() {
154         def yangResourceMapCapture
155         given: 'zip archive with multiple .yang files inside'
156             def multipartFile = createZipMultipartFileFromResource("/yang-files-set.zip")
157         and: 'an endpoint'
158             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
159         when: 'file uploaded with schema set create request'
160             def response =
161                     mvc.perform(
162                             multipart(schemaSetEndpoint)
163                                     .file(multipartFile)
164                                     .param('schema-set-name', schemaSetName))
165                             .andReturn().response
166         then: 'associated service method is invoked with expected parameters'
167             1 * mockCpsModuleService.createSchemaSet(dataspaceName, schemaSetName, _) >>
168                     { args -> yangResourceMapCapture = args[2] }
169             yangResourceMapCapture['assembly.yang'] == "fake assembly content 1\n"
170             yangResourceMapCapture['component.yang'] == "fake component content 1\n"
171         and: 'response code indicates success'
172             response.status == HttpStatus.CREATED.value()
173     }
174
175     def 'Create a schema set from a yang file that is greater than 1MB.'() {
176         given: 'a yang file greater than 1MB'
177             def multipartFile = createMultipartFileFromResource("/model-over-1mb.yang")
178         and: 'an endpoint'
179             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
180         when: 'a file is uploaded to the create schema set endpoint'
181             def response =
182                     mvc.perform(
183                             multipart(schemaSetEndpoint)
184                                     .file(multipartFile)
185                                     .param('schema-set-name', schemaSetName))
186                             .andReturn().response
187         then: 'the associated service method is invoked'
188             1 * mockCpsModuleService.createSchemaSet(dataspaceName, schemaSetName, _)
189         and: 'the response code indicates success'
190             response.status == HttpStatus.CREATED.value()
191     }
192
193     def 'Create schema set from zip archive having #caseDescriptor.'() {
194         given: 'an endpoint'
195             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
196         when: 'zip archive having #caseDescriptor is uploaded with create schema set request'
197             def response =
198                     mvc.perform(
199                             multipart(schemaSetEndpoint)
200                                     .file(multipartFile)
201                                     .param('schema-set-name', schemaSetName))
202                             .andReturn().response
203         then: 'create schema set rejected'
204             response.status == HttpStatus.BAD_REQUEST.value()
205         where: 'following cases are tested'
206             caseDescriptor                        | multipartFile
207             'no .yang files inside'               | createZipMultipartFileFromResource("/no-yang-files.zip")
208             'multiple .yang files with same name' | createZipMultipartFileFromResource("/yang-files-multiple-sets.zip")
209     }
210
211     def 'Create schema set from file with unsupported filename extension.'() {
212         given: 'file with unsupported filename extension (.doc)'
213             def multipartFile = createMultipartFile("filename.doc", "content")
214         and: 'an endpoint'
215             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
216         when: 'file uploaded with schema set create request'
217             def response =
218                     mvc.perform(
219                             multipart(schemaSetEndpoint)
220                                     .file(multipartFile)
221                                     .param('schema-set-name', schemaSetName))
222                             .andReturn().response
223         then: 'create schema set rejected'
224             response.status == HttpStatus.BAD_REQUEST.value()
225     }
226
227     def 'Create schema set from #fileType file with IOException occurrence on processing.'() {
228         given: 'an endpoint'
229             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
230         when: 'file uploaded with schema set create request'
231             def multipartFile = createMultipartFileForIOException(fileType)
232             def response =
233                     mvc.perform(
234                             multipart(schemaSetEndpoint)
235                                     .file(multipartFile)
236                                     .param('schema-set-name', schemaSetName))
237                             .andReturn().response
238         then: 'the error response returned indicating internal server error occurrence'
239             response.status == HttpStatus.INTERNAL_SERVER_ERROR.value()
240         where: 'following file types are used'
241             fileType << ['YANG', 'ZIP']
242     }
243
244     def 'Delete schema set.'() {
245         given: 'an endpoint'
246             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets/$schemaSetName"
247         when: 'delete schema set endpoint is invoked'
248             def response = mvc.perform(delete(schemaSetEndpoint)).andReturn().response
249         then: 'associated service method is invoked with expected parameters'
250             1 * mockCpsModuleService.deleteSchemaSet(dataspaceName, schemaSetName, CASCADE_DELETE_PROHIBITED)
251         and: 'response code indicates success'
252             response.status == HttpStatus.NO_CONTENT.value()
253     }
254
255     def 'Delete schema set which is in use.'() {
256         given: 'service method throws an exception indicating the schema set is in use'
257             def thrownException = new SchemaSetInUseException(dataspaceName, schemaSetName)
258             mockCpsModuleService.deleteSchemaSet(dataspaceName, schemaSetName, CASCADE_DELETE_PROHIBITED) >>
259                     { throw thrownException }
260         and: 'an endpoint'
261             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets/$schemaSetName"
262         when: 'delete schema set endpoint is invoked'
263             def response = mvc.perform(delete(schemaSetEndpoint)).andReturn().response
264         then: 'schema set deletion fails with conflict response code'
265             response.status == HttpStatus.CONFLICT.value()
266     }
267
268     def 'Get existing schema set.'() {
269         given: 'service method returns a new schema set'
270             mockCpsModuleService.getSchemaSet(dataspaceName, schemaSetName) >>
271                     new SchemaSet(name: schemaSetName, dataspaceName: dataspaceName)
272         and: 'an endpoint'
273             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets/$schemaSetName"
274         when: 'get schema set API is invoked'
275             def response = mvc.perform(get(schemaSetEndpoint)).andReturn().response
276         then: 'the correct schema set is returned'
277             response.status == HttpStatus.OK.value()
278             response.getContentAsString().contains(schemaSetName)
279     }
280
281     def 'Get all schema sets for a given dataspace name.'() {
282         given: 'service method returns all schema sets for a dataspace'
283             mockCpsModuleService.getSchemaSets(dataspaceName) >>
284                 [new SchemaSet(name: schemaSetName, dataspaceName: dataspaceName),
285                 new SchemaSet(name: "test-schemaset", dataspaceName: dataspaceName)]
286         and: 'an endpoint'
287             def schemaSetEndpoint = "$basePath/v1/dataspaces/$dataspaceName/schema-sets"
288         when: 'get schema sets API is invoked'
289             def response = mvc.perform(get(schemaSetEndpoint)).andReturn().response
290         then: 'the correct schema sets is returned'
291             assert response.status == HttpStatus.OK.value()
292             assert response.getContentAsString() == '[{"dataspaceName":"my_dataspace","moduleReferences":[],"name":' +
293                    '"my_schema_set"},{"dataspaceName":"my_dataspace","moduleReferences":[],"name":"test-schemaset"}]'
294     }
295
296     def 'Create Anchor.'() {
297         given: 'request parameters'
298             def requestParams = new LinkedMultiValueMap<>()
299             requestParams.add('schema-set-name', schemaSetName)
300             requestParams.add('anchor-name', anchorName)
301         and: 'an endpoint'
302             def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors"
303         when: 'post is invoked'
304             def response =
305                     mvc.perform(
306                             post(anchorEndpoint).contentType(MediaType.APPLICATION_JSON)
307                                     .params(requestParams as MultiValueMap))
308                             .andReturn().response
309         then: 'anchor is created successfully'
310             1 * mockCpsAdminService.createAnchor(dataspaceName, schemaSetName, anchorName)
311             response.status == HttpStatus.CREATED.value()
312             response.getContentAsString().contains(anchorName)
313     }
314
315     def 'Get existing anchor.'() {
316         given: 'service method returns a list of anchors'
317             mockCpsAdminService.getAnchors(dataspaceName) >> [anchor]
318         and: 'an endpoint'
319             def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors"
320         when: 'get all anchors API is invoked'
321             def response = mvc.perform(get(anchorEndpoint)).andReturn().response
322         then: 'the correct anchor is returned'
323             response.status == HttpStatus.OK.value()
324             response.getContentAsString().contains(anchorName)
325     }
326
327     def 'Get existing anchor by dataspace and anchor name.'() {
328         given: 'service method returns an anchor'
329             mockCpsAdminService.getAnchor(dataspaceName, anchorName) >>
330                     new Anchor(name: anchorName, dataspaceName: dataspaceName, schemaSetName: schemaSetName)
331         and: 'an endpoint'
332             def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors/$anchorName"
333         when: 'get anchor API is invoked'
334             def response = mvc.perform(get(anchorEndpoint)).andReturn().response
335             def responseContent = response.getContentAsString()
336         then: 'the correct anchor is returned'
337             response.status == HttpStatus.OK.value()
338             responseContent.contains(anchorName)
339             responseContent.contains(dataspaceName)
340             responseContent.contains(schemaSetName)
341     }
342
343     def 'Delete anchor.'() {
344         given: 'an endpoint'
345             def anchorEndpoint = "$basePath/v1/dataspaces/$dataspaceName/anchors/$anchorName"
346         when: 'delete method is invoked on anchor endpoint'
347             def response = mvc.perform(delete(anchorEndpoint)).andReturn().response
348         then: 'associated service method is invoked with expected parameters'
349             1 * mockCpsAdminService.deleteAnchor(dataspaceName, anchorName)
350         and: 'response code indicates success'
351             response.status == HttpStatus.NO_CONTENT.value()
352     }
353
354     def 'Delete dataspace.'() {
355         given: 'an endpoint'
356             def dataspaceEndpoint = "$basePath/v1/dataspaces"
357         when: 'delete dataspace endpoint is invoked'
358             def response = mvc.perform(delete(dataspaceEndpoint)
359                 .param('dataspace-name', dataspaceName))
360                 .andReturn().response
361         then: 'associated service method is invoked with expected parameter'
362             1 * mockCpsAdminService.deleteDataspace(dataspaceName)
363         and: 'response code indicates success'
364             response.status == HttpStatus.NO_CONTENT.value()
365     }
366
367     def createMultipartFile(filename, content) {
368         return new MockMultipartFile("file", filename, "text/plain", content.getBytes())
369     }
370
371     def createZipMultipartFileFromResource(resourcePath) {
372         return new MockMultipartFile("file", "test.zip", "application/zip",
373                 getClass().getResource(resourcePath).getBytes())
374     }
375
376     def createMultipartFileFromResource(resourcePath) {
377         return new MockMultipartFile("file", "test.yang", "application/text",
378                 getClass().getResource(resourcePath).getBytes())
379     }
380
381     def createMultipartFileForIOException(extension) {
382         def multipartFile = Mock(MockMultipartFile)
383         multipartFile.getOriginalFilename() >> "TEST." + extension
384         multipartFile.getBytes() >> { throw new IOException() }
385         multipartFile.getInputStream() >> { throw new IOException() }
386         return multipartFile
387     }
388
389 }