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