Merge "CPS-1020 : DuplicatedYangResourceException error at parallel cmHandle registra...
[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  *  Modifications 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.mapstruct.factory.Mappers
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.HttpClientRequestException
30 import org.onap.cps.ncmp.api.impl.exception.ServerNcmpException
31 import org.onap.cps.ncmp.rest.controller.NcmpRestInputMapper
32 import org.onap.cps.ncmp.rest.mapper.RestOutputCmHandleStateMapper
33 import org.onap.cps.ncmp.rest.executor.CpsNcmpTaskExecutor
34 import org.onap.cps.spi.exceptions.CpsException
35 import org.onap.cps.spi.exceptions.DataNodeNotFoundException
36 import org.onap.cps.spi.exceptions.DataValidationException
37 import org.onap.cps.utils.JsonObjectMapper
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.test.web.servlet.MockMvc
45 import spock.lang.Shared
46 import spock.lang.Specification
47
48 import static org.onap.cps.ncmp.rest.exceptions.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMP
49 import static org.onap.cps.ncmp.rest.exceptions.NetworkCmProxyRestExceptionHandlerSpec.ApiType.NCMPINVENTORY
50 import static org.springframework.http.HttpStatus.BAD_GATEWAY
51 import static org.springframework.http.HttpStatus.BAD_REQUEST
52 import static org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
53 import static org.springframework.http.HttpStatus.NOT_FOUND
54 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
55 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post
56
57 @WebMvcTest
58 class NetworkCmProxyRestExceptionHandlerSpec extends Specification {
59
60     @Autowired
61     MockMvc mvc
62
63     @SpringBean
64     NetworkCmProxyDataService mockNetworkCmProxyDataService = Mock()
65
66     @SpringBean
67     JsonObjectMapper stubbedJsonObjectMapper = Stub()
68
69     @SpringBean
70     NcmpRestInputMapper ncmpRestInputMapper = Mappers.getMapper(NcmpRestInputMapper)
71
72     @SpringBean
73     RestOutputCmHandleStateMapper restOutputCmHandleStateMapper = Mappers.getMapper(RestOutputCmHandleStateMapper)
74
75     @SpringBean
76     CpsNcmpTaskExecutor stubbedCpsTaskExecutor = Stub()
77
78     @Value('${rest.api.ncmp-base-path}')
79     def basePathNcmp
80
81     @Value('${rest.api.ncmp-inventory-base-path}')
82     def basePathNcmpInventory
83
84     def dataNodeBaseEndpointNcmp
85     def dataNodeBaseEndpointNcmpInventory
86
87     @Shared
88     def sampleErrorMessage = 'some error message'
89     @Shared
90     def sampleErrorDetails = 'some error details'
91
92     def setup() {
93         dataNodeBaseEndpointNcmp = "$basePathNcmp/v1"
94         dataNodeBaseEndpointNcmpInventory = "$basePathNcmpInventory/v1"
95     }
96
97     def 'Get request with generic #scenario exception returns correct HTTP Status with #scenario'() {
98         when: 'an exception is thrown by the service'
99             setupTestException(exception, NCMP)
100             def response = performTestRequest(NCMP)
101         then: 'an HTTP response is returned with correct message and details'
102             assertTestResponse(response, expectedErrorCode, expectedErrorMessage, expectedErrorDetails)
103         where:
104             scenario              | exception                                                        || expectedErrorDetails | expectedErrorMessage | expectedErrorCode
105             'CPS'                 | new CpsException(sampleErrorMessage, sampleErrorDetails)         || sampleErrorDetails   | sampleErrorMessage   | INTERNAL_SERVER_ERROR
106             'NCMP-server'         | new ServerNcmpException(sampleErrorMessage, sampleErrorDetails)  || null                 | sampleErrorMessage   | INTERNAL_SERVER_ERROR
107             'NCMP-client'         | new DmiRequestException(sampleErrorMessage, sampleErrorDetails)  || null                 | sampleErrorMessage   | BAD_REQUEST
108             'DataNode Validation' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || null                 | 'DataNode not found' | NOT_FOUND
109             'other'               | new IllegalStateException(sampleErrorMessage)                    || null                 | sampleErrorMessage   | INTERNAL_SERVER_ERROR
110             'Data Node Not Found' | new DataNodeNotFoundException('myDataspaceName', 'myAnchorName') || 'DataNode not found' | 'DataNode not found' | NOT_FOUND
111     }
112
113     def 'Post request with exception returns correct HTTP Status.'() {
114         given: 'the service throws data validation exception'
115             def exception = new DataValidationException(sampleErrorMessage, sampleErrorDetails)
116             setupTestException(exception, NCMPINVENTORY)
117         when: 'the HTTP request is made'
118             def response = performTestRequest(NCMPINVENTORY)
119         then: 'an HTTP response is returned with correct message and details'
120             assertTestResponse(response, BAD_REQUEST, sampleErrorMessage, sampleErrorDetails)
121     }
122
123     def 'Failing DMI Request - passthrough scenario'() {
124         given: 'failing DMI request'
125             setupTestException(new HttpClientRequestException('Error Message Details NCMP', 'Bad Request from DMI', 400) , NCMP)
126         when: 'the DMI request is executed'
127             def response = performTestRequest(NCMP)
128         then: 'NCMP service responds with 502 Bad Gateway status'
129             response.status == HttpStatus.BAD_GATEWAY.value()
130         and: 'the NCMP response also contains the original DMI response details'
131             response.contentAsString.contains('400')
132             response.contentAsString.contains('Bad Request from DMI')
133     }
134
135     def setupTestException(exception, apiType) {
136         if (NCMP == apiType) {
137             mockNetworkCmProxyDataService.getYangResourcesModuleReferences(*_) >> { throw exception }
138         }
139         mockNetworkCmProxyDataService.updateDmiRegistrationAndSyncModule(*_) >> { throw exception }
140     }
141
142     def performTestRequest(apiType) {
143         if (NCMP == apiType) {
144             return mvc.perform(get("$dataNodeBaseEndpointNcmp/ch/testCmHandle/modules")).andReturn().response
145         }
146         def jsonData = TestUtils.getResourceFileContent('dmi_registration_all_singing_and_dancing.json')
147         return mvc.perform(post("$dataNodeBaseEndpointNcmpInventory/ch").contentType(MediaType.APPLICATION_JSON).content(jsonData)).andReturn().response
148     }
149
150     static void assertTestResponse(response, expectedStatus , expectedErrorMessage , expectedErrorDetails) {
151         assert response.status == expectedStatus.value()
152         def content = new JsonSlurper().parseText(response.contentAsString)
153         assert content['status'].toString().contains(expectedStatus.toString())
154         assert content['message'].toString().contains(expectedErrorMessage)
155         assert expectedErrorDetails == null || content['details'].toString().contains(expectedErrorDetails)
156     }
157
158     enum ApiType {
159         NCMP,
160         NCMPINVENTORY;
161     }
162 }