003dbf5b04eb19c45d48f7f931c5fd4f25cbe235
[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-2023 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 com.fasterxml.jackson.databind.JsonNode
25 import com.fasterxml.jackson.databind.ObjectMapper
26 import com.fasterxml.jackson.databind.node.ObjectNode
27 import org.onap.cps.ncmp.api.impl.config.DmiWebClientConfiguration;
28 import org.onap.cps.ncmp.api.impl.exception.HttpClientRequestException
29 import org.onap.cps.ncmp.utils.TestUtils
30 import org.spockframework.spring.SpringBean
31 import org.springframework.beans.factory.annotation.Autowired
32 import org.springframework.boot.test.context.SpringBootTest
33
34 import org.springframework.http.HttpHeaders
35 import org.springframework.http.HttpStatus
36 import org.springframework.http.ResponseEntity
37 import org.springframework.test.context.ContextConfiguration
38 import org.springframework.test.context.TestPropertySource
39 import org.springframework.web.client.HttpServerErrorException
40 import org.springframework.web.reactive.function.client.WebClient
41 import reactor.core.publisher.Mono
42 import spock.lang.Specification
43
44 import static org.onap.cps.ncmp.api.impl.operations.OperationType.READ
45 import static org.onap.cps.ncmp.api.impl.operations.OperationType.PATCH
46 import static org.onap.cps.ncmp.api.impl.operations.OperationType.CREATE
47
48 @SpringBootTest
49 @ContextConfiguration(classes = [DmiWebClientConfiguration, DmiRestClient, ObjectMapper])
50 class DmiRestClientSpec extends Specification {
51
52     static final NO_AUTH_HEADER = null
53     static final BASIC_AUTH_HEADER = 'Basic c29tZS11c2VyOnNvbWUtcGFzc3dvcmQ='
54     static final BEARER_AUTH_HEADER = 'Bearer my-bearer-token'
55
56     @Autowired
57     DmiWebClientConfiguration.DmiProperties dmiProperties
58
59     @Autowired
60     DmiRestClient objectUnderTest
61
62     @SpringBean
63     WebClient mockWebClient = Mock(WebClient);
64
65     @Autowired
66     ObjectMapper objectMapper
67
68     def mockRequestBodyUriSpec = Mock(WebClient.RequestBodyUriSpec)
69     def mockResponseSpec = Mock(WebClient.ResponseSpec)
70     def mockResponseEntity = Mock(ResponseEntity)
71     def monoSpec = Mono.just(mockResponseEntity)
72     def 'DMI POST operation with JSON.'() {
73         given: 'the web client returns a valid response entity for the expected parameters'
74             mockWebClient.post() >> mockRequestBodyUriSpec
75             mockWebclientResponse()
76             mockRequestBodyUriSpec.body(_) >> mockRequestBodyUriSpec
77             mockResponseSpec.toEntity(Object.class) >> monoSpec
78             monoSpec.block() >> mockResponseEntity
79         when: 'POST operation is invoked'
80             def result = objectUnderTest.postOperationWithJsonData('/my/url', 'some json', READ, null)
81         then: 'the output of the method is equal to the output from the test template'
82             result == mockResponseEntity
83     }
84
85     def 'Failing DMI POST operation.'() {
86         given: 'the rest template returns a valid response entity'
87             def serverResponse = 'server response'.getBytes()
88             def httpServerErrorException = new HttpServerErrorException(HttpStatus.FORBIDDEN, 'status text', serverResponse, null)
89             mockWebClient.post() >> { throw httpServerErrorException }
90         when: 'POST operation is invoked'
91             def result = objectUnderTest.postOperationWithJsonData('/some', 'some json', operation, null)
92         then: 'a Http Client Exception is thrown'
93             def thrown = thrown(HttpClientRequestException)
94         and: 'the exception has the relevant details from the error response'
95             assert thrown.httpStatus == 403
96             assert thrown.message == "Unable to ${operation} resource data."
97             assert thrown.details == 'server response'
98         where: 'the following operation is executed'
99             operation << [CREATE, READ, PATCH]
100     }
101
102     def 'Dmi trust level is determined by spring boot health status'() {
103         given: 'a health check response'
104             def dmiPluginHealthCheckResponseJsonData = TestUtils.getResourceFileContent('dmiPluginHealthCheckResponse.json')
105             def jsonNode = objectMapper.readValue(dmiPluginHealthCheckResponseJsonData, JsonNode.class)
106             ((ObjectNode) jsonNode).put('status', 'my status')
107             def monoResponse = Mono.just(jsonNode)
108             mockWebClient.get() >> mockRequestBodyUriSpec
109             mockWebclientResponse()
110             mockResponseSpec.bodyToMono(_) >> monoResponse
111             monoResponse.block() >> jsonNode
112         when: 'get trust level of the dmi plugin'
113             def result = objectUnderTest.getDmiHealthStatus('some/url')
114         then: 'the status value from the json is return'
115             assert result == 'my status'
116     }
117
118     def 'Failing to get dmi plugin health status #scenario'() {
119         given: 'rest template with #scenario'
120             mockWebClient.get() >> healthStatusResponse
121         when: 'attempt to get health status of the dmi plugin'
122             def result = objectUnderTest.getDmiHealthStatus('some url')
123         then: 'result will be empty'
124             assert result == ''
125         where: 'the following responses are used'
126             scenario    | healthStatusResponse
127             'null'      | null
128             'exception' | {throw new Exception()}
129     }
130
131     def 'DMI auth header #scenario'() {
132         when: 'Specific dmi properties are provided'
133             dmiProperties.dmiBasicAuthEnabled = authEnabled
134         then: 'http headers to conditionally have Authorization header'
135             def authHeaderValues = objectUnderTest.configureHttpHeaders(new HttpHeaders(), ncmpAuthHeader).getOrEmpty('Authorization')
136             def outputAuthHeader = (authHeaderValues == null ? null : authHeaderValues[0])
137             assert outputAuthHeader == expectedAuthHeader
138         where: 'the following configurations are used'
139             scenario                                          | authEnabled | ncmpAuthHeader     || expectedAuthHeader
140             'DMI basic auth enabled, no NCMP bearer token'    | true        | NO_AUTH_HEADER     || BASIC_AUTH_HEADER
141             'DMI basic auth enabled, with NCMP bearer token'  | true        | BEARER_AUTH_HEADER || BASIC_AUTH_HEADER
142             'DMI basic auth disabled, no NCMP bearer token'   | false       | NO_AUTH_HEADER     || NO_AUTH_HEADER
143             'DMI basic auth disabled, with NCMP bearer token' | false       | BEARER_AUTH_HEADER || BEARER_AUTH_HEADER
144             'DMI basic auth disabled, with NCMP basic auth'   | false       | BASIC_AUTH_HEADER  || NO_AUTH_HEADER
145     }
146
147     def mockWebclientResponse() {
148         mockRequestBodyUriSpec.uri(_) >> mockRequestBodyUriSpec
149         mockRequestBodyUriSpec.headers(_) >> mockRequestBodyUriSpec
150         mockRequestBodyUriSpec.retrieve() >> mockResponseSpec
151     }
152 }