bfad88a141f75519034f65e406deda11d07d377b
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2024 OpenInfra Foundation Europe. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.utils.v3;
22
23 import com.fasterxml.jackson.core.JsonProcessingException;
24 import com.fasterxml.jackson.databind.ObjectMapper;
25 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
26 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
27 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
28 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
29 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
30 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
31 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2.Consts;
32 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2.RappSimulatorController;
33 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
34 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
35 import org.springframework.beans.factory.annotation.Autowired;
36 import org.springframework.context.ApplicationContext;
37 import org.springframework.http.HttpStatus;
38 import org.springframework.http.HttpStatusCode;
39 import org.springframework.http.MediaType;
40 import org.springframework.http.ResponseEntity;
41 import org.springframework.stereotype.Component;
42 import org.springframework.web.reactive.function.client.WebClientResponseException;
43 import reactor.core.publisher.Mono;
44 import reactor.test.StepVerifier;
45 import reactor.util.annotation.Nullable;
46
47 import java.util.ArrayList;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Map;
51
52 import static org.assertj.core.api.Assertions.assertThat;
53 import static org.junit.jupiter.api.Assertions.*;
54
55 @Component
56 public class TestHelper {
57
58     @Autowired
59     ApplicationConfig applicationConfig;
60
61     @Autowired
62     ApplicationContext context;
63
64     @Autowired
65     private Rics rics;
66
67     @Autowired
68     private Policies policies;
69
70     @Autowired
71     private PolicyTypes policyTypes;
72
73     @Autowired
74     private ObjectMapper objectMapper;
75
76     public int port;
77
78     public AsyncRestClient restClientV3() {
79         return restClientV3(false);
80     }
81
82     public AsyncRestClient restClient() {
83         return restClient(false);
84     }
85
86     public AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
87         WebClientConfig config = this.applicationConfig.getWebClientConfig();
88         config = WebClientConfig.builder()
89                 .keyStoreType(config.getKeyStoreType())
90                 .keyStorePassword(config.getKeyStorePassword())
91                 .keyStore(config.getKeyStore())
92                 .keyPassword(config.getKeyPassword())
93                 .isTrustStoreUsed(useTrustValidation)
94                 .trustStore(config.getTrustStore())
95                 .trustStorePassword(config.getTrustStorePassword())
96                 .httpProxyConfig(config.getHttpProxyConfig())
97                 .build();
98
99         AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
100         return f.createRestClientNoHttpProxy(baseUrl);
101
102     }
103
104     public String baseUrl() {
105         return "https://localhost:" + port;
106     }
107
108     public AsyncRestClient restClientV3(boolean useTrustValidation) {
109         return restClient(baseUrl() + Consts.V3_API_ROOT, useTrustValidation);
110     }
111
112     public AsyncRestClient restClient(boolean useTrustValidation) {
113         return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
114     }
115
116     public void putService(String name) throws JsonProcessingException {
117         putService(name, 0, null);
118     }
119
120     public void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) throws JsonProcessingException {
121         String url = "/services";
122         String body = createServiceJson(name, keepAliveIntervalSeconds);
123         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
124         if (expectedStatus != null) {
125             assertNotNull(resp);
126             assertEquals(expectedStatus, resp.getStatusCode(), "");
127         }
128     }
129
130     public PolicyType createPolicyType(String policyTypeName) {
131         return PolicyType.builder()
132                 .id(policyTypeName)
133                 .schema("{\"title\":\"" + policyTypeName + "\"}")
134                 .build();
135     }
136
137     public Ric addRic(String ricId) {
138         return addRic(ricId, null);
139     }
140
141     public RicConfig ricConfig(String ricId, String managedElement) {
142         List<String> mes = new ArrayList<>();
143         if (managedElement != null) {
144             mes.add(managedElement);
145         }
146         return RicConfig.builder()
147                 .ricId(ricId)
148                 .baseUrl(ricId)
149                 .managedElementIds(mes)
150                 .build();
151     }
152     public Ric addRic(String ricId, String managedElement) {
153         if (rics.get(ricId) != null) {
154             return rics.get(ricId);
155         }
156
157         RicConfig conf = ricConfig(ricId, managedElement);
158         Ric ric = new Ric(conf);
159         ric.setState(Ric.RicState.AVAILABLE);
160         this.rics.put(ric);
161         return ric;
162     }
163     public PolicyType addPolicyType(String policyTypeName, String ricId) {
164         PolicyType type = createPolicyType(policyTypeName);
165         policyTypes.put(type);
166         addRic(ricId).addSupportedPolicyType(type);
167         return type;
168     }
169
170     public Map<String,String> jsonString() {
171         Map<String,String> policyDataInMap = new HashMap<>();
172         policyDataInMap.put("servingCellNrcgi","1");
173         return policyDataInMap;
174     }
175
176     public String postPolicyBody(String nearRtRicId, String policyTypeName) throws JsonProcessingException {
177         PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, jsonString());
178         policyObjectInfo.setPolicyTypeId(policyTypeName);
179         policyObjectInfo.setPolicyObject(dummyPolicyObject());
180         return objectMapper.writeValueAsString(policyObjectInfo);
181     }
182
183     public PolicyObjectInformation policyObjectInfo(String nearRtRicId, String policyTypeName) {
184         PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, jsonString());
185         policyObjectInfo.setPolicyTypeId(policyTypeName);
186         policyObjectInfo.setPolicyObject(dummyPolicyObject());
187         return policyObjectInfo;
188     }
189
190     private Map<String,String> dummyPolicyObject() {
191         Map<String,String> policyDataInMap = new HashMap<>();
192         policyDataInMap.put("servingCellNrcgi","1");
193         return policyDataInMap;
194     }
195
196     public String createServiceJson(String name, long keepAliveIntervalSeconds) throws JsonProcessingException {
197         String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
198         return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
199     }
200
201     public String createServiceJson(String name, long keepAliveIntervalSeconds, String url) throws JsonProcessingException {
202         org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceRegistrationInfo service = new org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceRegistrationInfo(name)
203                 .keepAliveIntervalSeconds(keepAliveIntervalSeconds)
204                 .callbackUrl(url);
205
206         return objectMapper.writeValueAsString(service);
207     }
208
209     public void testSuccessResponse(Mono<ResponseEntity<String>> responseEntityMono, HttpStatus httpStatusCode,
210                                     String responseContains) {
211         StepVerifier.create(responseEntityMono)
212                 .expectNextMatches(responseEntity -> {
213                     // Assert status code
214                     HttpStatusCode status = responseEntity.getStatusCode();
215                     String res = responseEntity.getBody();
216                     assertThat(res).contains(responseContains);
217                     return status.value() == httpStatusCode.value();
218                 })
219                 .expectComplete()
220                 .verify();
221     }
222
223     public void testErrorCode(Mono<?> request, HttpStatus expStatus) {
224         testErrorCode(request, expStatus, "", true);
225     }
226
227     public void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
228         testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
229     }
230
231     public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
232         testErrorCode(request, expStatus, responseContains, true);
233     }
234
235     public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
236                                boolean expectApplicationProblemJsonMediaType) {
237         StepVerifier.create(request)
238                 .expectSubscription()
239                 .expectErrorMatches(
240                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType))
241                 .verify();
242     }
243
244     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
245                                         boolean expectApplicationProblemJsonMediaType) {
246         assertTrue(throwable instanceof WebClientResponseException);
247         WebClientResponseException responseException = (WebClientResponseException) throwable;
248         String body = responseException.getResponseBodyAsString();
249         assertThat(body).contains(responseContains);
250         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
251
252         if (expectApplicationProblemJsonMediaType) {
253             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
254         }
255         return true;
256     }
257
258     public void verifyMockError(Mono<?> responseMono, String responseCheck) {
259         StepVerifier.create(responseMono)
260                 .expectSubscription()
261                 .expectErrorMatches(response -> {
262                     String status = response.getMessage();
263                     return status.contains(responseCheck);
264                 })
265                 .verify();
266     }
267 }