summaryrefslogtreecommitdiffstats
path: root/src/test/groovy/org/onap/cps/ncmp/dmi/rest/controller/DmiRestControllerSpec.groovy
blob: 221603c2c1db31dd0a99efb2216b16421d90cf20 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
 *  ============LICENSE_START=======================================================
 *  Copyright (C) 2021 Nordix Foundation
 *  Modifications Copyright (C) 2021 Bell Canada
 *  ================================================================================
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  SPDX-License-Identifier: Apache-2.0
 *  ============LICENSE_END=========================================================
 */

package org.onap.cps.ncmp.dmi.rest.controller

import com.fasterxml.jackson.databind.ObjectMapper
import org.onap.cps.ncmp.dmi.TestUtils
import org.onap.cps.ncmp.dmi.exception.DmiException
import org.onap.cps.ncmp.dmi.exception.ModuleResourceNotFoundException
import org.onap.cps.ncmp.dmi.exception.ModulesNotFoundException
import org.onap.cps.ncmp.dmi.service.model.ModuleReference
import org.onap.cps.ncmp.dmi.model.ModuleSet
import org.onap.cps.ncmp.dmi.model.ModuleSetSchemas
import org.onap.cps.ncmp.dmi.model.YangResource
import org.onap.cps.ncmp.dmi.model.YangResources
import org.onap.cps.ncmp.dmi.service.DmiService
import org.spockframework.spring.SpringBean
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.context.annotation.Import
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.test.context.support.WithMockUser
import org.springframework.test.web.servlet.MockMvc
import spock.lang.Specification

import static org.onap.cps.ncmp.dmi.model.DataAccessRequest.OperationEnum.DELETE
import static org.onap.cps.ncmp.dmi.model.DataAccessRequest.OperationEnum.READ
import static org.springframework.http.HttpStatus.BAD_REQUEST
import static org.springframework.http.HttpStatus.NO_CONTENT
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
import static org.onap.cps.ncmp.dmi.model.DataAccessRequest.OperationEnum.CREATE
import static org.onap.cps.ncmp.dmi.model.DataAccessRequest.OperationEnum.UPDATE
import static org.springframework.http.HttpStatus.CREATED
import static org.springframework.http.HttpStatus.OK

@WebMvcTest(DmiRestController)
@WithMockUser
@Import(ObjectMapper)
class DmiRestControllerSpec extends Specification {

    @SpringBean
    DmiService mockDmiService = Mock()

    @Autowired
    private MockMvc mvc

    @Value('${rest.api.dmi-base-path}/v1')
    def basePathV1

    def 'Get all modules.'() {
        given: 'REST endpoint for getting all modules'
            def getModuleUrl = "$basePathV1/ch/node1/modules"
        and: 'get modules for cm-handle returns a json'
            def json = '{"cmHandleProperties" : {}}'
            def moduleSetSchema = new ModuleSetSchemas(namespace:'some-namespace',
                                                        moduleName:'some-moduleName',
                                                        revision:'some-revision')
            def moduleSetSchemasList = [moduleSetSchema] as List<ModuleSetSchemas>
            def moduleSet = new ModuleSet()
            moduleSet.schemas(moduleSetSchemasList)
            mockDmiService.getModulesForCmHandle('node1') >> moduleSet
        when: 'post is being called'
            def response = mvc.perform(post(getModuleUrl)
                    .contentType(MediaType.APPLICATION_JSON).content(json))
                    .andReturn().response
        then: 'status is OK'
            response.status == OK.value()
        and: 'the response content matches the result from the DMI service'
            response.getContentAsString() == '{"schemas":[{"moduleName":"some-moduleName","revision":"some-revision","namespace":"some-namespace"}]}'
    }

    def 'Get all modules with exception handling of #scenario.'() {
        given: 'REST endpoint for getting all modules'
            def getModuleUrl = "$basePathV1/ch/node1/modules"
        and: 'given request body and get modules for cm-handle throws #exceptionClass'
            def json = '{"cmHandleProperties" : {}}'
            mockDmiService.getModulesForCmHandle('node1') >> { throw Mock(exceptionClass) }
        when: 'post is invoked'
            def response = mvc.perform( post(getModuleUrl)
                    .contentType(MediaType.APPLICATION_JSON).content(json))
                    .andReturn().response
        then: 'response status is #expectedResponse'
            response.status == expectedResponse
        where: 'the scenario is #scenario'
            scenario                       |  exceptionClass                 || expectedResponse
            'dmi service exception'        |  DmiException.class             || HttpStatus.INTERNAL_SERVER_ERROR.value()
            'no modules found'             |  ModulesNotFoundException.class || HttpStatus.NOT_FOUND.value()
            'any other runtime exception'  |  RuntimeException.class         || HttpStatus.INTERNAL_SERVER_ERROR.value()
    }

    def 'Register given list.'() {
        given: 'register cm handle url and cm handles json'
            def registerCmhandlesPost = "${basePathV1}/inventory/cmHandles"
            def cmHandleJson = '{"cmHandles":["node1", "node2"]}'
        when: 'register cm handles api is invoked with POST'
            def response = mvc.perform(
                    post(registerCmhandlesPost)
                            .contentType(MediaType.APPLICATION_JSON)
                            .content(cmHandleJson)
            ).andReturn().response
        then: 'register cm handles in dmi service is invoked with correct parameters'
            1 * mockDmiService.registerCmHandles(_ as List<String>)
        and: 'response status is created'
            response.status == CREATED.value()
    }

    def 'register cm handles called with empty content.'() {
        given: 'register cm handle url and empty json'
            def registerCmhandlesPost = "${basePathV1}/inventory/cmHandles"
            def emptyJson = '{"cmHandles":[]}'
        when: 'register cm handles post api is invoked with no content'
            def response = mvc.perform(
                    post(registerCmhandlesPost).contentType(MediaType.APPLICATION_JSON)
                            .content(emptyJson)
            ).andReturn().response
        then: 'response status is "bad request"'
            response.status == BAD_REQUEST.value()
        and: 'dmi service is not called'
            0 * mockDmiService.registerCmHandles(_)
    }

    def 'Retrieve module resources.'() {
        given: 'an endpoint and json data'
            def getModulesEndpoint = "$basePathV1/ch/some-cm-handle/moduleResources"
            String jsonData = TestUtils.getResourceFileContent('GetModules.json')
        and: 'the DMI service returns the yang resources'
            ModuleReference moduleReference1 = new ModuleReference(name: 'ietf-yang-library', revision: '2016-06-21')
            ModuleReference moduleReference2 = new ModuleReference(name: 'nc-notifications', revision: '2008-07-14')
            def moduleReferences = [moduleReference1, moduleReference2]
            def yangResources = new YangResources()
            def yangResource = new YangResource(yangSource: '"some-data"', moduleName: 'NAME', revision: 'REVISION')
            yangResources.add(yangResource)
            mockDmiService.getModuleResources('some-cm-handle', moduleReferences) >> yangResources
        when: 'get module resource api is invoked'
            def response = mvc.perform(post(getModulesEndpoint)
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(jsonData)).andReturn().response
        then: 'a OK status is returned'
            response.status == OK.value()
        and: 'the expected response is returned'
            response.getContentAsString() == '[{"yangSource":"\\"some-data\\"","moduleName":"NAME","revision":"REVISION"}]'
    }

    def 'Retrieve module resources with exception handling.'() {
        given: 'an endpoint and json data'
            def getModulesEndpoint = "$basePathV1/ch/some-cm-handle/moduleResources"
            String jsonData = TestUtils.getResourceFileContent('GetModules.json')
        and: 'the service method is invoked to get module resources and throws an exception'
            mockDmiService.getModuleResources('some-cm-handle', _) >> { throw Mock(ModuleResourceNotFoundException.class) }
        when: 'get module resource api is invoked'
            def response = mvc.perform(post(getModulesEndpoint)
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(jsonData)).andReturn().response
        then: 'a not found status is returned'
            response.status == HttpStatus.NOT_FOUND.value()
    }

    def 'Get resource data for pass-through operational.'() {
        given: 'Get resource data url'
            def getResourceDataForCmHandleUrl = "${basePathV1}/ch/some-cmHandle/data/ds/ncmp-datastore:passthrough-operational" +
                    "?resourceIdentifier=parent/child&options=(fields=myfields,depth=5)"
            def json = '{"cmHandleProperties" : { "prop1" : "value1", "prop2" : "value2"}}'
        when: 'get resource data POST api is invoked'
            def response = mvc.perform(
                    post(getResourceDataForCmHandleUrl).contentType(MediaType.APPLICATION_JSON)
                            .accept(MediaType.APPLICATION_JSON).content(json)
            ).andReturn().response
        then: 'response status is ok'
            response.status == OK.value()
        and: 'dmi service called with get resource data'
            1 * mockDmiService.getResourceData('some-cmHandle',
                    'parent/child',
                    'application/json',
                    '(fields=myfields,depth=5)',
                    'content=all')
    }

    def 'Get resource data for pass-through operational with bad request.'() {
        given: 'Get resource data url'
            def getResourceDataForCmHandleUrl = "${basePathV1}/ch/some-cmHandle/data/ds/ncmp-datastore:passthrough-operational" +
                "?resourceIdentifier=parent/child&options=(fields=myfields,depth=5)"
            def jsonData = TestUtils.getResourceFileContent('createDataWithNormalChar.json')
        when: 'get resource data POST api is invoked'
            def response = mvc.perform(
                post(getResourceDataForCmHandleUrl).contentType(MediaType.APPLICATION_JSON)
                    .accept(MediaType.APPLICATION_JSON).content(jsonData)
            ).andReturn().response
        then: 'response status is bad request'
            response.status == BAD_REQUEST.value()
        and: 'dmi service is not invoked'
            0 * mockDmiService.getResourceData(*_)
    }

    def 'write data with #scenario operation using passthrough running.'() {
        given: 'write data for passthrough running url and jsonData'
            def writeDataForPassthroughRunning = "${basePathV1}/ch/some-cmHandle/data/ds/ncmp-datastore:passthrough-running" +
                    "?resourceIdentifier=some-resourceIdentifier"
            def jsonData = TestUtils.getResourceFileContent(requestBodyFile)
        and: 'dmi service is called'
            mockDmiService.writeData(operationEnum, 'some-cmHandle',
                    'some-resourceIdentifier', 'application/json',
                    'normal request body' ) >> '{some-json}'
        when: 'write data for passthrough running post api is invoked with json data'
            def response = mvc.perform(
                    post(writeDataForPassthroughRunning).contentType(MediaType.APPLICATION_JSON)
                            .content(jsonData)
            ).andReturn().response
       then: 'response status is #expectedResponseStatus'
            response.status == expectedResponseStatus
        and: 'the data in the request body is as expected'
            response.getContentAsString() == expectedJsonResponse
        where: 'given request body and data'
            scenario   | requestBodyFile                 | operationEnum                                  || expectedResponseStatus | expectedJsonResponse
            'Create'   | 'createDataWithNormalChar.json' | CREATE                                         || CREATED.value()        | '{some-json}'
            'Update'   | 'updateData.json'               | UPDATE                                         || OK.value()             | '{some-json}'
            'Delete'   | 'deleteData.json'               | DELETE                                         || NO_CONTENT.value()     | '{some-json}'
            'Read'     | 'readData.json'                 | READ                                           || OK.value()             | ''
    }

    def 'Create data using passthrough for special characters.'(){
         given: 'create data for cmHandle url and JsonData'
            def writeDataForCmHandlePassthroughRunning = "${basePathV1}/ch/some-cmHandle/data/ds/ncmp-datastore:passthrough-running" +
             "?resourceIdentifier=some-resourceIdentifier"
            def jsonData = TestUtils.getResourceFileContent('createDataWithSpecialChar.json')
         and: 'dmi service is called'
            mockDmiService.writeData(CREATE, 'some-cmHandle', 'some-resourceIdentifier', 'application/json',
                'data with quote \" and new line \n') >> '{some-json}'
         when: 'create cmHandle passthrough running post api is invoked with json data with special chars'
            def response = mvc.perform(
                post(writeDataForCmHandlePassthroughRunning).contentType(MediaType.APPLICATION_JSON).content(jsonData)
            ).andReturn().response
         then: 'response status is CREATED'
            response.status == CREATED.value()
         and: 'the data in the request body is as expected'
            response.getContentAsString() == '{some-json}'
    }


    def 'Get resource data for pass-through running with #scenario value in resource identifier param.'() {
        given: 'Get resource data url'
            def getResourceDataForCmHandleUrl = "${basePathV1}/ch/some-cmHandle/data/ds/ncmp-datastore:passthrough-running" +
                    "?resourceIdentifier="+resourceIdentifier+"&options=(fields=myfields,depth=5)"
            def json = '{"cmHandleProperties" : { "prop1" : "value1", "prop2" : "value2"}}'
        when: 'get resource data POST api is invoked'
            def response = mvc.perform(
                    post(getResourceDataForCmHandleUrl).contentType(MediaType.APPLICATION_JSON)
                            .accept(MediaType.APPLICATION_JSON).content(json)
            ).andReturn().response
        then: 'response status is ok'
            response.status == OK.value()
        and: 'dmi service called with get resource data for a cm handle'
            1 * mockDmiService.getResourceData('some-cmHandle',
                    resourceIdentifier,
                    'application/json',
                    '(fields=myfields,depth=5)',
                    'content=config')
        where: 'tokens are used in the resource identifier parameter'
            scenario                       | resourceIdentifier
            '/'                            | 'id/with/slashes'
            '?'                            | 'idWith?'
            ','                            | 'idWith,'
            '='                            | 'idWith='
            '[]'                           | 'idWith[]'
            '? needs to be encoded as %3F' | 'idWith%3F'

    }
}