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