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