CPS-2182 - #4 Add module Set tag to NCMPs DMI Batch Data interface
[cps.git] / cps-ncmp-service / src / test / groovy / org / onap / cps / ncmp / api / impl / client / DmiRestClientSpec.groovy
1 /*
2  *  ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2024 Nordix Foundation
4  *  Modifications Copyright (C) 2022 Bell Canada
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.api.impl.client
23
24 import static org.onap.cps.ncmp.api.impl.operations.OperationType.READ
25 import static org.onap.cps.ncmp.api.impl.operations.OperationType.PATCH
26 import static org.onap.cps.ncmp.api.impl.operations.OperationType.CREATE
27 import static org.springframework.http.HttpStatus.SERVICE_UNAVAILABLE
28 import static org.onap.cps.ncmp.api.NcmpResponseStatus.DMI_SERVICE_NOT_RESPONDING
29 import static org.onap.cps.ncmp.api.NcmpResponseStatus.UNABLE_TO_READ_RESOURCE_DATA
30
31 import com.fasterxml.jackson.databind.JsonNode
32 import com.fasterxml.jackson.databind.ObjectMapper
33 import com.fasterxml.jackson.databind.node.ObjectNode
34 import org.onap.cps.ncmp.api.impl.config.DmiWebClientConfiguration
35 import org.onap.cps.ncmp.api.impl.exception.InvalidDmiResourceUrlException
36 import org.onap.cps.ncmp.api.impl.exception.DmiClientRequestException
37 import org.onap.cps.ncmp.utils.TestUtils
38 import org.onap.cps.utils.JsonObjectMapper
39 import org.spockframework.spring.SpringBean
40 import org.springframework.beans.factory.annotation.Autowired
41 import org.springframework.boot.test.context.SpringBootTest
42 import org.springframework.http.HttpHeaders
43 import org.springframework.http.ResponseEntity
44 import org.springframework.test.context.ContextConfiguration
45 import org.springframework.web.client.HttpServerErrorException
46 import org.springframework.web.reactive.function.client.WebClient
47 import reactor.core.publisher.Mono
48 import spock.lang.Specification
49 import org.springframework.web.reactive.function.client.WebClientResponseException
50
51 @SpringBootTest
52 @ContextConfiguration(classes = [DmiWebClientConfiguration, DmiRestClient, ObjectMapper])
53 class DmiRestClientSpec extends Specification {
54
55     static final NO_AUTH_HEADER = null
56     static final BASIC_AUTH_HEADER = 'Basic c29tZS11c2VyOnNvbWUtcGFzc3dvcmQ='
57     static final BEARER_AUTH_HEADER = 'Bearer my-bearer-token'
58
59     @Autowired
60     DmiWebClientConfiguration.DmiProperties dmiProperties
61
62     @Autowired
63     DmiRestClient objectUnderTest
64
65     @SpringBean
66     WebClient mockWebClient = Mock(WebClient);
67
68     @SpringBean
69     JsonObjectMapper jsonObjectMapper = new JsonObjectMapper(new ObjectMapper())
70
71     def mockRequestBodyUriSpec = Mock(WebClient.RequestBodyUriSpec)
72     def mockResponseSpec = Mock(WebClient.ResponseSpec)
73     def mockResponseEntity = Mock(ResponseEntity)
74
75     def setup() {
76         mockRequestBodyUriSpec.uri(_) >> mockRequestBodyUriSpec
77         mockRequestBodyUriSpec.headers(_) >> mockRequestBodyUriSpec
78         mockRequestBodyUriSpec.retrieve() >> mockResponseSpec
79     }
80
81     def 'DMI POST operation with JSON.'() {
82         given: 'the web client returns a valid response entity for the expected parameters'
83             mockWebClient.post() >> mockRequestBodyUriSpec
84             mockRequestBodyUriSpec.body(_) >> mockRequestBodyUriSpec
85             def monoSpec = Mono.just(mockResponseEntity)
86             mockResponseSpec.bodyToMono(Object.class) >>  monoSpec
87             monoSpec.block() >> mockResponseEntity
88         when: 'POST operation is invoked'
89             def response = objectUnderTest.postOperationWithJsonData('/my/url', 'some json', READ, null)
90         then: 'the output of the method is equal to the output from the test template'
91             assert response.statusCode.value() == 200
92             assert response.hasBody()
93     }
94
95     def 'Failing DMI POST operation for server error'() {
96         given: 'the web client throws an exception'
97             mockWebClient.post() >> { throw new HttpServerErrorException(SERVICE_UNAVAILABLE, null, null, null) }
98         when: 'POST operation is invoked'
99             objectUnderTest.postOperationWithJsonData('/some', 'some json', READ, null)
100         then: 'a http client exception is thrown'
101             def thrown = thrown(DmiClientRequestException)
102         and: 'the exception has the relevant details from the error response'
103             assert thrown.ncmpResponseStatus.code == '102'
104             assert thrown.httpStatusCode == 503
105     }
106
107     def 'Failing DMI POST operation due to invalid dmi resource url.'() {
108         when: 'POST operation is invoked with invalid dmi resource url'
109             objectUnderTest.postOperationWithJsonData('/invalid dmi url', null, null, null)
110         then: 'invalid dmi resource url exception is thrown'
111             def thrown = thrown(InvalidDmiResourceUrlException)
112         and: 'the exception has the relevant details from the error response'
113             assert thrown.httpStatus == 400
114             assert thrown.message == 'Invalid dmi resource url: /invalid dmi url'
115         where: 'the following operations are executed'
116             operation << [CREATE, READ, PATCH]
117     }
118
119     def 'Dmi service sends client error response when #scenario'() {
120         given: 'the web client unable to return response entity but error'
121             mockWebClient.post() >> mockRequestBodyUriSpec
122             mockRequestBodyUriSpec.body(_) >> mockRequestBodyUriSpec
123             def monoSpec = Mono.error(new WebClientResponseException('message', httpStatusCode, null, null, null, null))
124             mockResponseSpec.bodyToMono(Object.class) >>  monoSpec
125         when: 'POST operation is invoked'
126             objectUnderTest.postOperationWithJsonData('/my/url', 'some json', READ, null)
127         then: 'a http client exception is thrown'
128             def thrown = thrown(DmiClientRequestException)
129         and: 'the exception has the relevant details from the error response'
130             assert thrown.ncmpResponseStatus.code == expectedNcmpResponseStatusCode
131             assert thrown.httpStatusCode == httpStatusCode
132         where: 'the following errors occur'
133             scenario              | httpStatusCode | expectedNcmpResponseStatusCode
134             'dmi request timeout' | 408            | DMI_SERVICE_NOT_RESPONDING.code
135             'other error code'    | 500            | UNABLE_TO_READ_RESOURCE_DATA.code
136     }
137
138     def 'Dmi trust level is determined by spring boot health status'() {
139         given: 'a health check response'
140             def dmiPluginHealthCheckResponseJsonData = TestUtils.getResourceFileContent('dmiPluginHealthCheckResponse.json')
141             def jsonNode = jsonObjectMapper.convertJsonString(dmiPluginHealthCheckResponseJsonData, JsonNode.class)
142             ((ObjectNode) jsonNode).put('status', 'my status')
143             def monoResponse = Mono.just(jsonNode)
144             mockWebClient.get() >> mockRequestBodyUriSpec
145             mockResponseSpec.bodyToMono(_) >> monoResponse
146             monoResponse.block() >> jsonNode
147         when: 'get trust level of the dmi plugin'
148             def result = objectUnderTest.getDmiHealthStatus('some/url')
149         then: 'the status value from the json is return'
150             assert result == 'my status'
151     }
152
153     def 'Failing to get dmi plugin health status #scenario'() {
154         given: 'rest template with #scenario'
155             mockWebClient.get() >> healthStatusResponse
156         when: 'attempt to get health status of the dmi plugin'
157             def result = objectUnderTest.getDmiHealthStatus('some url')
158         then: 'result will be empty'
159             assert result == ''
160         where: 'the following responses are used'
161             scenario    | healthStatusResponse
162             'null'      | null
163             'exception' | {throw new Exception()}
164     }
165
166     def 'DMI auth header #scenario'() {
167         when: 'Specific dmi properties are provided'
168             dmiProperties.dmiBasicAuthEnabled = authEnabled
169         then: 'http headers to conditionally have Authorization header'
170             def authHeaderValues = objectUnderTest.configureHttpHeaders(new HttpHeaders(), ncmpAuthHeader).getOrEmpty('Authorization')
171             def outputAuthHeader = (authHeaderValues == null ? null : authHeaderValues[0])
172             assert outputAuthHeader == expectedAuthHeader
173         where: 'the following configurations are used'
174             scenario                                          | authEnabled | ncmpAuthHeader     || expectedAuthHeader
175             'DMI basic auth enabled, no NCMP bearer token'    | true        | NO_AUTH_HEADER     || BASIC_AUTH_HEADER
176             'DMI basic auth enabled, with NCMP bearer token'  | true        | BEARER_AUTH_HEADER || BASIC_AUTH_HEADER
177             'DMI basic auth disabled, no NCMP bearer token'   | false       | NO_AUTH_HEADER     || NO_AUTH_HEADER
178             'DMI basic auth disabled, with NCMP bearer token' | false       | BEARER_AUTH_HEADER || BEARER_AUTH_HEADER
179             'DMI basic auth disabled, with NCMP basic auth'   | false       | BASIC_AUTH_HEADER  || NO_AUTH_HEADER
180     }
181 }