f6b1ce82a606bba65260130b24f4dee4142cc341
[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 com.google.common.io.CharStreams;
26 import com.google.gson.Gson;
27 import com.google.gson.JsonObject;
28 import com.google.gson.JsonParser;
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.controllers.v2.RappSimulatorController;
37 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
38 import org.onap.ccsdk.oran.a1policymanagementservice.repository.*;
39 import org.springframework.beans.factory.annotation.Autowired;
40 import org.springframework.context.ApplicationContext;
41 import org.springframework.http.HttpStatus;
42 import org.springframework.http.HttpStatusCode;
43 import org.springframework.http.MediaType;
44 import org.springframework.http.ResponseEntity;
45 import org.springframework.stereotype.Component;
46 import org.springframework.web.reactive.function.client.WebClientResponseException;
47 import reactor.core.publisher.Mono;
48 import reactor.test.StepVerifier;
49 import reactor.util.annotation.Nullable;
50
51 import java.io.IOException;
52 import java.io.InputStream;
53 import java.io.InputStreamReader;
54 import java.nio.charset.StandardCharsets;
55 import java.time.Instant;
56 import java.util.ArrayList;
57 import java.util.List;
58
59 import static org.assertj.core.api.Assertions.assertThat;
60 import static org.junit.jupiter.api.Assertions.*;
61
62 @Component
63 public class TestHelper {
64
65     @Autowired
66     ApplicationConfig applicationConfig;
67
68     @Autowired
69     ApplicationContext context;
70
71     @Autowired
72     private Rics rics;
73
74     @Autowired
75     private Policies policies;
76
77     @Autowired
78     private PolicyTypes policyTypes;
79
80     @Autowired
81     private ObjectMapper objectMapper;
82
83     @Autowired
84     private Gson gson;
85
86     public int port;
87
88     public AsyncRestClient restClientV3() {
89         return restClientV3(false);
90     }
91
92     public AsyncRestClient restClient() {
93         return restClient(false);
94     }
95
96     public AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
97         WebClientConfig config = this.applicationConfig.getWebClientConfig();
98         config = WebClientConfig.builder()
99                 .keyStoreType(config.getKeyStoreType())
100                 .keyStorePassword(config.getKeyStorePassword())
101                 .keyStore(config.getKeyStore())
102                 .keyPassword(config.getKeyPassword())
103                 .isTrustStoreUsed(useTrustValidation)
104                 .trustStore(config.getTrustStore())
105                 .trustStorePassword(config.getTrustStorePassword())
106                 .httpProxyConfig(config.getHttpProxyConfig())
107                 .build();
108
109         AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
110         return f.createRestClientNoHttpProxy(baseUrl);
111
112     }
113
114     public String baseUrl() {
115         return "https://localhost:" + port;
116     }
117
118     public AsyncRestClient restClientV3(boolean useTrustValidation) {
119         return restClient(baseUrl() + Consts.V3_API_ROOT, useTrustValidation);
120     }
121
122     public AsyncRestClient restClient(boolean useTrustValidation) {
123         return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
124     }
125
126     public void putService(String name) throws JsonProcessingException {
127         putService(name, 0, null);
128     }
129
130     public void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) throws JsonProcessingException {
131         String url = "/services";
132         String body = createServiceJson(name, keepAliveIntervalSeconds);
133         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
134         if (expectedStatus != null) {
135             assertNotNull(resp);
136             assertEquals(expectedStatus, resp.getStatusCode(), "");
137         }
138     }
139
140     public PolicyType createPolicyType(String policyTypeName, String filePath) throws IOException {
141         InputStream in = getClass().getResourceAsStream(filePath);
142         assert in != null;
143         String schema = CharStreams.toString(new InputStreamReader(in, StandardCharsets.UTF_8));
144         return PolicyType.builder()
145                 .id(policyTypeName)
146                 .schema(schema)
147                 .build();
148     }
149
150     public Ric addRic(String ricId) {
151         return addRic(ricId, null);
152     }
153
154     public RicConfig ricConfig(String ricId, String managedElement) {
155         List<String> mes = new ArrayList<>();
156         if (managedElement != null) {
157             mes.add(managedElement);
158         }
159         return RicConfig.builder()
160                 .ricId(ricId)
161                 .baseUrl(ricId)
162                 .managedElementIds(mes)
163                 .build();
164     }
165     public Ric addRic(String ricId, String managedElement) {
166         if (rics.get(ricId) != null) {
167             return rics.get(ricId);
168         }
169
170         RicConfig conf = ricConfig(ricId, managedElement);
171         Ric ric = new Ric(conf);
172         ric.setState(Ric.RicState.AVAILABLE);
173         this.rics.put(ric);
174         return ric;
175     }
176     public PolicyType addPolicyType(String policyTypeName, String ricId) throws IOException {
177         PolicyType type = createPolicyType(policyTypeName, "/policy_types/demo-policy-schema-3.json");
178         policyTypes.put(type);
179         addRic(ricId).addSupportedPolicyType(type);
180         return type;
181     }
182
183     public String postPolicyBody(String nearRtRicId, String policyTypeName) {
184         PolicyObjectInformation policyObjectInfo = new PolicyObjectInformation(nearRtRicId, dummyPolicyObject(), policyTypeName);
185         return gson.toJson(policyObjectInfo);
186     }
187
188     public PolicyObjectInformation policyObjectInfo(String nearRtRicId, String policyTypeName) {
189         return gson.fromJson(postPolicyBody(nearRtRicId, policyTypeName), PolicyObjectInformation.class);
190     }
191
192     public JsonObject dummyPolicyObject() {
193         return JsonParser.parseString("{\n" +
194                 "        \"scope\": {\n" +
195                 "            \"ueId\": \"ue5100\",\n" +
196                 "            \"qosId\": \"qos5100\"\n" +
197                 "        },\n" +
198                 "        \"qosObjectives\": {\n" +
199                 "            \"priorityLevel\": 5100.0\n" +
200                 "        }\n" +
201                 "    }").getAsJsonObject();
202     }
203
204     public Policy buidTestPolicy(PolicyObjectInformation policyInfo, String id) throws Exception{
205         return Policy.builder().ric(rics.getRic(policyInfo.getNearRtRicId()))
206                 .type(policyTypes.getType(policyInfo.getPolicyTypeId()))
207                 .json(objectMapper.writeValueAsString(policyInfo.getPolicyObject()))
208                 .lastModified(Instant.now())
209                 .id(id).build();
210     }
211
212     public String createServiceJson(String name, long keepAliveIntervalSeconds) throws JsonProcessingException {
213         String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
214         return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
215     }
216
217     public String createServiceJson(String name, long keepAliveIntervalSeconds, String url) throws JsonProcessingException {
218         org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceRegistrationInfo service = new org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceRegistrationInfo(name)
219                 .keepAliveIntervalSeconds(keepAliveIntervalSeconds)
220                 .callbackUrl(url);
221
222         return objectMapper.writeValueAsString(service);
223     }
224
225     public void testSuccessResponse(Mono<ResponseEntity<String>> responseEntityMono, HttpStatus httpStatusCode,
226                                     String responseContains) {
227         StepVerifier.create(responseEntityMono)
228                 .expectNextMatches(responseEntity -> {
229                     // Assert status code
230                     HttpStatusCode status = responseEntity.getStatusCode();
231                     String res = responseEntity.getBody();
232                     assertThat(res).contains(responseContains);
233                     return status.value() == httpStatusCode.value();
234                 })
235                 .expectComplete()
236                 .verify();
237     }
238
239     public void testErrorCode(Mono<?> request, HttpStatus expStatus) {
240         testErrorCode(request, expStatus, "", true);
241     }
242
243     public void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
244         testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
245     }
246
247     public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
248         testErrorCode(request, expStatus, responseContains, true);
249     }
250
251     public void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
252                                boolean expectApplicationProblemJsonMediaType) {
253         StepVerifier.create(request)
254                 .expectSubscription()
255                 .expectErrorMatches(
256                         t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType))
257                 .verify();
258     }
259
260     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
261                                         boolean expectApplicationProblemJsonMediaType) {
262         assertTrue(throwable instanceof WebClientResponseException);
263         WebClientResponseException responseException = (WebClientResponseException) throwable;
264         String body = responseException.getResponseBodyAsString();
265         assertThat(body).contains(responseContains);
266         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
267
268         if (expectApplicationProblemJsonMediaType) {
269             assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
270         }
271         return true;
272     }
273
274     public void verifyMockError(Mono<?> responseMono, String responseCheck) {
275         StepVerifier.create(responseMono)
276                 .expectSubscription()
277                 .expectErrorMatches(response -> {
278                     String status = response.getMessage();
279                     return status.contains(responseCheck);
280                 })
281                 .verify();
282     }
283 }