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