2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2024-2025 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.utils.v3;
23 import com.fasterxml.jackson.databind.ObjectMapper;
24 import com.google.common.io.CharStreams;
25 import com.google.gson.Gson;
26 import com.google.gson.JsonObject;
27 import com.google.gson.JsonParser;
28 import org.apache.commons.io.FileUtils;
29 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
30 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
31 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
32 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
33 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
34 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
35 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2.Consts;
36 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
37 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
38 import org.springframework.beans.factory.annotation.Autowired;
39 import org.springframework.context.ApplicationContext;
40 import org.springframework.http.HttpStatus;
41 import org.springframework.http.HttpStatusCode;
42 import org.springframework.http.MediaType;
43 import org.springframework.http.ResponseEntity;
44 import org.springframework.stereotype.Component;
45 import org.springframework.web.reactive.function.client.WebClientResponseException;
46 import reactor.core.publisher.Mono;
47 import reactor.test.StepVerifier;
50 import java.io.IOException;
51 import java.io.InputStream;
52 import java.io.InputStreamReader;
53 import java.nio.charset.StandardCharsets;
54 import java.time.Instant;
55 import java.util.ArrayList;
56 import java.util.List;
57 import java.util.Objects;
58 import java.util.function.Predicate;
60 import static org.assertj.core.api.Assertions.assertThat;
61 import static org.junit.jupiter.api.Assertions.assertTrue;
64 public class TestHelperTest {
67 ApplicationConfig applicationConfig;
70 ApplicationContext context;
76 private Policies policies;
79 private PolicyTypes policyTypes;
82 private ObjectMapper objectMapper;
89 public AsyncRestClient restClientV3() {
90 return restClientV3(false);
93 public AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
94 WebClientConfig config = this.applicationConfig.getWebClientConfig();
95 config = WebClientConfig.builder()
96 .keyStoreType(config.getKeyStoreType())
97 .keyStorePassword(config.getKeyStorePassword())
98 .keyStore(config.getKeyStore())
99 .keyPassword(config.getKeyPassword())
100 .isTrustStoreUsed(useTrustValidation)
101 .trustStore(config.getTrustStore())
102 .trustStorePassword(config.getTrustStorePassword())
103 .httpProxyConfig(config.getHttpProxyConfig())
106 AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
107 return f.createRestClientNoHttpProxy(baseUrl);
111 public String baseUrl() {
112 return "https://localhost:" + port;
115 public AsyncRestClient restClientV3(boolean useTrustValidation) {
116 return restClient(baseUrl() + Consts.V3_API_ROOT, useTrustValidation);
119 public AsyncRestClient restClient(boolean useTrustValidation) {
120 return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
123 public PolicyType createPolicyType(String policyTypeName, String filePath) throws IOException {
124 InputStream in = getClass().getResourceAsStream(filePath);
126 String schema = CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
127 return PolicyType.builder()
133 public Ric addRic(String ricId) {
134 return addRic(ricId, null);
137 public RicConfig ricConfig(String ricId, String managedElement) {
138 List<String> mes = new ArrayList<>();
139 if (managedElement != null) {
140 mes.add(managedElement);
142 return RicConfig.builder()
145 .managedElementIds(mes)
148 public Ric addRic(String ricId, String managedElement) {
149 if (rics.get(ricId) != null) {
150 return rics.get(ricId);
153 RicConfig conf = ricConfig(ricId, managedElement);
154 Ric ric = new Ric(conf);
155 ric.setState(Ric.RicState.AVAILABLE);
159 public PolicyType addPolicyType(String policyTypeName, String ricId) throws IOException {
160 PolicyType type = createPolicyType(policyTypeName, "/policy_types/demo-policy-schema-3.json");
161 policyTypes.put(type);
162 addRic(ricId).addSupportedPolicyType(type);
166 public String postPolicyBody(String nearRtRicId, String policyTypeName, String policyId) {
167 PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, dummyPolicyObject(), policyTypeName);
168 if (policyId != null && !policyId.isEmpty() && !policyId.isBlank())
169 policyObjectInfo.setPolicyId(policyId);
170 return gson.toJson(policyObjectInfo);
173 public String postBadPolicyBody(String nearRtRicId, String policyTypeName, String policyId) {
174 PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, dummyBadPolicyObject(), policyTypeName);
175 if (policyId != null && !policyId.isEmpty() && !policyId.isBlank())
176 policyObjectInfo.setPolicyId(policyId);
177 return gson.toJson(policyObjectInfo);
180 public String putPolicyBody(String nearRtRicId, String policyTypeName, String policyId, String ueId, String qosId,
181 String priorityLevel) {
182 PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, dummyPolicyObjectForPut(
183 ueId, qosId, priorityLevel), policyTypeName);
184 if (policyId != null && !policyId.isEmpty() && !policyId.isBlank())
185 policyObjectInfo.setPolicyId(policyId);
186 return gson.toJson(policyObjectInfo);
189 public String putBadPolicyBody(String nearRtRicId, String policyTypeName, String policyId, String ueId, String qosId,
190 String priorityLevel, String foo) {
191 PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, dummyBadPolicyObjectForPut(
192 ueId, qosId, priorityLevel, foo), policyTypeName);
193 if (policyId != null && !policyId.isEmpty() && !policyId.isBlank())
194 policyObjectInfo.setPolicyId(policyId);
195 return gson.toJson(policyObjectInfo);
198 public PolicyObjectInformation policyObjectInfo(String nearRtRicId, String policyTypeName) {
199 return gson.fromJson(postPolicyBody(nearRtRicId, policyTypeName, ""), PolicyObjectInformation.class);
202 public JsonObject dummyPolicyObjectForPut(String... values) {
203 return JsonParser.parseString("{\n" +
205 " \"ueId\": \"" + values[0] + "\",\n" +
206 " \"qosId\": \"" + values[1] + "\"\n" +
208 " \"qosObjectives\": {\n" +
209 " \"priorityLevel\": " + values[2] + "\n" +
211 " }").getAsJsonObject();
214 public JsonObject dummyBadPolicyObjectForPut(String... values) {
215 return JsonParser.parseString("{\n" +
217 " \"ueId\": \"" + values[0] + "\",\n" +
218 " \"qosId\": \"" + values[1] + "\",\n" +
219 " \"foo\": \"" + values[3] + "\"\n" +
221 " \"qosObjectives\": {\n" +
222 " \"priorityLevel\": " + values[2] + "\n" +
224 " }").getAsJsonObject();
227 public JsonObject dummyPolicyObject() {
228 return JsonParser.parseString("{\n" +
230 " \"ueId\": \"ue5100\",\n" +
231 " \"qosId\": \"qos5100\"\n" +
233 " \"qosObjectives\": {\n" +
234 " \"priorityLevel\": 5100.0\n" +
236 " }").getAsJsonObject();
239 public JsonObject dummyBadPolicyObject() {
240 return JsonParser.parseString("{\n" +
242 " \"ueId\": \"ue5100\",\n" +
243 " \"qosId\": \"qos5100\",\n" +
244 " \"foo\": \"bar\"\n" +
246 " \"qosObjectives\": {\n" +
247 " \"priorityLevel\": 5100.0\n" +
249 " }").getAsJsonObject();
252 public Policy buidTestPolicy(PolicyObjectInformation policyInfo, String id) throws Exception{
253 return Policy.builder().ric(rics.getRic(policyInfo.getNearRtRicId()))
254 .type(policyTypes.getType(policyInfo.getPolicyTypeId()))
255 .json(objectMapper.writeValueAsString(policyInfo.getPolicyObject()))
256 .lastModified(Instant.now())
260 public <T> void testSuccessResponse(Mono<ResponseEntity<T>> responseEntityMono, HttpStatus httpStatusCode,
261 Predicate<T> responsePredicate) {
262 StepVerifier.create(responseEntityMono)
263 .expectNextMatches(responseEntity -> {
264 // Assert status code
265 HttpStatusCode status = responseEntity.getStatusCode();
266 T responseBody = responseEntity.getBody();
267 assert responsePredicate.test(responseBody);
268 return status.value() == httpStatusCode.value();
274 public void testSuccessHeader(Mono<ResponseEntity<String>> responseEntityMono, String headerKey,
275 Predicate<String> responsePredicate) {
276 StepVerifier.create(responseEntityMono)
277 .expectNextMatches(responseEntity -> {
278 String headerValue = Objects.requireNonNull(responseEntity.getHeaders().get(headerKey)).get(0);
279 return responsePredicate.test(headerValue);
285 public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
286 testErrorCode(request, expStatus, responseContains, true);
289 public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
290 boolean expectApplicationProblemJsonMediaType) {
291 StepVerifier.create(request)
292 .expectSubscription()
294 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType))
298 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
299 boolean expectApplicationProblemJsonMediaType) {
300 assertTrue(throwable instanceof WebClientResponseException);
301 WebClientResponseException responseException = (WebClientResponseException) throwable;
302 String body = responseException.getResponseBodyAsString();
303 assertThat(body).contains(responseContains);
304 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
306 if (expectApplicationProblemJsonMediaType) {
307 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
312 public void verifyMockError(Mono<?> responseMono, String responseCheck) {
313 StepVerifier.create(responseMono)
314 .expectSubscription()
315 .expectErrorMatches(response -> {
316 String status = response.getMessage();
317 return status.contains(responseCheck);
322 public String configAsString() throws Exception {
324 new File(Objects.requireNonNull(getClass().getClassLoader().getResource("test_application_configuration.json")).getFile());
325 return FileUtils.readFileToString(configFile, "UTF-8");
328 public String configAsStringMeNull() throws Exception {
330 new File(Objects.requireNonNull(getClass().getClassLoader().getResource("test_application_configuration_me_null.json")).getFile());
331 return FileUtils.readFileToString(configFile, "UTF-8");
334 public String configAsStringMeEmpty() throws Exception {
336 new File(Objects.requireNonNull(getClass().getClassLoader().getResource("test_application_configuration_me_empty.json")).getFile());
337 return FileUtils.readFileToString(configFile, "UTF-8");