b0b5858a3ba61726d5d386c4cfe471d4d8627559
[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.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;
48
49 import java.io.File;
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;
59
60 import static org.assertj.core.api.Assertions.assertThat;
61 import static org.junit.jupiter.api.Assertions.assertTrue;
62
63 @Component
64 public class TestHelper {
65
66     @Autowired
67     ApplicationConfig applicationConfig;
68
69     @Autowired
70     ApplicationContext context;
71
72     @Autowired
73     private Rics rics;
74
75     @Autowired
76     private Policies policies;
77
78     @Autowired
79     private PolicyTypes policyTypes;
80
81     @Autowired
82     private ObjectMapper objectMapper;
83
84     @Autowired
85     private Gson gson;
86
87     public int port;
88
89     public AsyncRestClient restClientV3() {
90         return restClientV3(false);
91     }
92
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())
104                 .build();
105
106         AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
107         return f.createRestClientNoHttpProxy(baseUrl);
108
109     }
110
111     public String baseUrl() {
112         return "https://localhost:" + port;
113     }
114
115     public AsyncRestClient restClientV3(boolean useTrustValidation) {
116         return restClient(baseUrl() + Consts.V3_API_ROOT, useTrustValidation);
117     }
118
119     public AsyncRestClient restClient(boolean useTrustValidation) {
120         return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
121     }
122
123     public PolicyType createPolicyType(String policyTypeName, String filePath) throws IOException {
124         InputStream in = getClass().getResourceAsStream(filePath);
125         assert in != null;
126         String schema = CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
127         return PolicyType.builder()
128                 .id(policyTypeName)
129                 .schema(schema)
130                 .build();
131     }
132
133     public Ric addRic(String ricId) {
134         return addRic(ricId, null);
135     }
136
137     public RicConfig ricConfig(String ricId, String managedElement) {
138         List<String> mes = new ArrayList<>();
139         if (managedElement != null) {
140             mes.add(managedElement);
141         }
142         return RicConfig.builder()
143                 .ricId(ricId)
144                 .baseUrl(ricId)
145                 .managedElementIds(mes)
146                 .build();
147     }
148     public Ric addRic(String ricId, String managedElement) {
149         if (rics.get(ricId) != null) {
150             return rics.get(ricId);
151         }
152
153         RicConfig conf = ricConfig(ricId, managedElement);
154         Ric ric = new Ric(conf);
155         ric.setState(Ric.RicState.AVAILABLE);
156         this.rics.put(ric);
157         return ric;
158     }
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);
163         return type;
164     }
165
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);
171     }
172
173     public String putPolicyBody(String nearRtRicId, String policyTypeName, String policyId, String ueId, String qosId,
174                                 String priorityLevel) {
175         PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, dummyPolicyObjectForPut(
176                 ueId, qosId, priorityLevel), policyTypeName);
177         if (policyId != null && !policyId.isEmpty() && !policyId.isBlank())
178             policyObjectInfo.setPolicyId(policyId);
179         return gson.toJson(policyObjectInfo);
180     }
181
182     public PolicyObjectInformation policyObjectInfo(String nearRtRicId, String policyTypeName) {
183         return gson.fromJson(postPolicyBody(nearRtRicId, policyTypeName, ""), PolicyObjectInformation.class);
184     }
185
186     public JsonObject dummyPolicyObjectForPut(String... values) {
187         return JsonParser.parseString("{\n" +
188                 "        \"scope\": {\n" +
189                 "            \"ueId\": \"" + values[0] + "\",\n" +
190                 "            \"qosId\": \"" + values[1] + "\"\n" +
191                 "        },\n" +
192                 "        \"qosObjectives\": {\n" +
193                 "            \"priorityLevel\": " + values[2] + "\n" +
194                 "        }\n" +
195                 "    }").getAsJsonObject();
196     }
197
198     public JsonObject dummyPolicyObject() {
199         return JsonParser.parseString("{\n" +
200                 "        \"scope\": {\n" +
201                 "            \"ueId\": \"ue5100\",\n" +
202                 "            \"qosId\": \"qos5100\"\n" +
203                 "        },\n" +
204                 "        \"qosObjectives\": {\n" +
205                 "            \"priorityLevel\": 5100.0\n" +
206                 "        }\n" +
207                 "    }").getAsJsonObject();
208     }
209
210     public Policy buidTestPolicy(PolicyObjectInformation policyInfo, String id) throws Exception{
211         return Policy.builder().ric(rics.getRic(policyInfo.getNearRtRicId()))
212                 .type(policyTypes.getType(policyInfo.getPolicyTypeId()))
213                 .json(objectMapper.writeValueAsString(policyInfo.getPolicyObject()))
214                 .lastModified(Instant.now())
215                 .id(id).build();
216     }
217
218     public <T> void testSuccessResponse(Mono<ResponseEntity<T>> responseEntityMono, HttpStatus httpStatusCode,
219                                                Predicate<T> responsePredicate) {
220         StepVerifier.create(responseEntityMono)
221                 .expectNextMatches(responseEntity -> {
222                     // Assert status code
223                     HttpStatusCode status = responseEntity.getStatusCode();
224                     T responseBody = responseEntity.getBody();
225                     assert responsePredicate.test(responseBody);
226                     return status.value() == httpStatusCode.value();
227                 })
228                 .expectComplete()
229                 .verify();
230     }
231
232     public void testSuccessHeader(Mono<ResponseEntity<String>> responseEntityMono, String headerKey,
233                                   Predicate<String> responsePredicate) {
234         StepVerifier.create(responseEntityMono)
235                 .expectNextMatches(responseEntity -> {
236                     String headerValue = Objects.requireNonNull(responseEntity.getHeaders().get(headerKey)).get(0);
237                     return responsePredicate.test(headerValue);
238                 })
239                 .expectComplete()
240                 .verify();
241     }
242
243     public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
244         testErrorCode(request, expStatus, responseContains, true);
245     }
246
247     public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
248                                boolean expectApplicationProblemJsonMediaType) {
249         StepVerifier.create(request)
250                 .expectSubscription()
251                 .expectErrorMatches(
252                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType))
253                 .verify();
254     }
255
256     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
257                                         boolean expectApplicationProblemJsonMediaType) {
258         assertTrue(throwable instanceof WebClientResponseException);
259         WebClientResponseException responseException = (WebClientResponseException) throwable;
260         String body = responseException.getResponseBodyAsString();
261         assertThat(body).contains(responseContains);
262         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
263
264         if (expectApplicationProblemJsonMediaType) {
265             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
266         }
267         return true;
268     }
269
270     public void verifyMockError(Mono<?> responseMono, String responseCheck) {
271         StepVerifier.create(responseMono)
272                 .expectSubscription()
273                 .expectErrorMatches(response -> {
274                     String status = response.getMessage();
275                     return status.contains(responseCheck);
276                 })
277                 .verify();
278     }
279
280     public String configAsString() throws Exception {
281         File configFile =
282                 new File(Objects.requireNonNull(getClass().getClassLoader().getResource("test_application_configuration.json")).getFile());
283         return FileUtils.readFileToString(configFile, "UTF-8");
284     }
285 }