Merge "Async: NCMP Rest impl. including Request ID generation"
[cps.git] / cps-ncmp-rest / src / test / groovy / org / onap / cps / ncmp / rest / exceptions / NetworkCmProxyRestExceptionHandlerSpec.groovy
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 highstreet technologies GmbH
4  *  Modification Copyright (C) 2021-2022 Nordix Foundation
5  *  ================================================================================
6  *  Licensed under the Apache License, Version 2.0 (the "License");
7  *  you may not use this file except in compliance with the License.
8  *  You may obtain a copy of the License at
9  *
10  *        http://www.apache.org/licenses/LICENSE-2.0
11  *
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.ncmp.rest.exceptions
23
24 import groovy.json.JsonSlurper
25 import org.modelmapper.ModelMapper
26 import org.onap.cps.TestUtils
27 import org.onap.cps.ncmp.api.NetworkCmProxyDataService
28 import org.onap.cps.ncmp.api.impl.exception.DmiRequestException
29 import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException
30 import org.onap.cps.ncmp.rest.controller.RestInputMapper
31 import org.onap.cps.spi.exceptions.CpsException
32 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
33 import org.onap.cps.spi.exceptions.DataValidationException
34 import org.onap.cps.utils.JsonObjectMapper
35 import org.spockframework.spring.SpringBean
36 import org.springframework.beans.factory.annotation.Autowired
37 import org.springframework.beans.factory.annotation.Value
38 import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
39 import org.springframework.http.MediaType
40 import org.springframework.test.web.servlet.MockMvc
41 import spock.lang.Shared
42 import spock.lang.Specification
43
44 import static org.onap.cps.ncmp.rest.exceptions.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMP
45 import static org.onap.cps.ncmp.rest.exceptions.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMPINVENTORY
46 import static org.springframework.http.HttpStatus.BAD_REQUEST
47 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
48 import static org.springframework.http.HttpStatus.NOT_FOUND
49 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
50 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
51
52 @WebMvcTest
53 class NetworkCmProxyRestExceptionHandlerSpec extends Specification {
54
55     @Autowired
56     MockMvc mvc
57
58     @SpringBean
59     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
60
61     @SpringBean
62     ModelMapper modelMapper = Stub()
63
64     @SpringBean
65     JsonObjectMapper jsonObjectMapper = Stub()
66
67     @SpringBean
68     RestInputMapper restInputMapper = Mock()
69
70     @Value('${rest.api.ncmp-base-path}')
71     def basePathNcmp
72
73     @Value('${rest.api.ncmp-inventory-base-path}')
74     def basePathNcmpInventory
75
76     def dataNodeBaseEndpointNcmp
77     def dataNodeBaseEndpointNcmpInventory
78
79     @Shared
80     def sampleErrorMessage = 'some error message'
81     @Shared
82     def sampleErrorDetails = 'some error details'
83
84     def setup() {
85         dataNodeBaseEndpointNcmp = "$basePathNcmp/v1"
86         dataNodeBaseEndpointNcmpInventory = "$basePathNcmpInventory/v1"
87     }
88
89     def 'Get request with generic #scenario exception returns correct HTTP Status with #scenario'() {
90         when: 'an exception is thrown by the service'
91             setupTestException(exception, NCMP)
92             def response = performTestRequest(NCMP)
93         then: 'an HTTP response is returned with correct message and details'
94             assertTestResponse(response, expectedErrorCode, expectedErrorMessage, expectedErrorDetails)
95         where:
96             scenario              | exception                                                        || expectedErrorDetails | expectedErrorMessage | expectedErrorCode
97             'CPS'                 | new CpsException(sampleErrorMessage, sampleErrorDetails)         || sampleErrorDetails   | sampleErrorMessage   | INTERNAL_SERVER_ERROR
98             'NCMP-server'         | new ServerNcmpException(sampleErrorMessage, sampleErrorDetails)  || null                 | sampleErrorMessage   | INTERNAL_SERVER_ERROR
99             'NCMP-client'         | new DmiRequestException(sampleErrorMessage, sampleErrorDetails)  || null                 | sampleErrorMessage   | BAD_REQUEST
100             'DataNode Validation' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || null                 | 'DataNode not found' | NOT_FOUND
101             'other'               | new IllegalStateException(sampleErrorMessage)                    || null                 | sampleErrorMessage   | INTERNAL_SERVER_ERROR
102             'Data Node Not Found' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || 'DataNode not found' | 'DataNode not found' | NOT_FOUND
103     }
104
105     def 'Post request with exception returns correct HTTP Status.'() {
106         given: 'the service throws data validation exception'
107             def exception = new DataValidationException(sampleErrorMessage, sampleErrorDetails)
108             setupTestException(exception, NCMPINVENTORY)
109         when: 'the HTTP request is made'
110             def response = performTestRequest(NCMPINVENTORY)
111         then: 'an HTTP response is returned with correct message and details'
112             assertTestResponse(response, BAD_REQUEST, sampleErrorMessage, sampleErrorDetails)
113     }
114
115     def setupTestException(exception, apiType) {
116         if (NCMP == apiType) {
117             mockNetworkCmProxyDataService.getYangResourcesModuleReferences(*_) >> { throw exception }
118         }
119         mockNetworkCmProxyDataService.updateDmiRegistrationAndSyncModule(*_) >> { throw exception }
120     }
121
122     def performTestRequest(apiType) {
123         if (NCMP == apiType) {
124             return mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/modules")).andReturn().response
125         }
126         def jsonData = TestUtils.getResourceFileContent('dmi_registration_all_singing_and_dancing.json')
127         return mvc.perform(post("$dataNodeBaseEndpointNcmpInventory/ch").contentType(MediaType.APPLICATION_JSON).content(jsonData)).andReturn().response
128     }
129
130     static void assertTestResponse(response, expectedStatus , expectedErrorMessage , expectedErrorDetails) {
131         assert response.status == expectedStatus.value()
132         def content = new JsonSlurper().parseText(response.contentAsString)
133         assert content['status'].toString().contains(expectedStatus.toString())
134         assert content['message'].toString().contains(expectedErrorMessage)
135         assert expectedErrorDetails == null || content['details'].toString().contains(expectedErrorDetails)
136     }
137
138     enum ApiType {
139         NCMP,
140         NCMPINVENTORY;
141     }
142 }