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