2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2020 Nordix Foundation. 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.controllers.v2;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.doReturn;
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
33 import java.io.FileNotFoundException;
34 import java.io.FileOutputStream;
35 import java.io.PrintStream;
36 import java.nio.charset.StandardCharsets;
37 import java.time.Duration;
38 import java.time.Instant;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.List;
43 import org.json.JSONObject;
44 import org.junit.jupiter.api.AfterEach;
45 import org.junit.jupiter.api.BeforeEach;
46 import org.junit.jupiter.api.Test;
47 import org.junit.jupiter.api.extension.ExtendWith;
48 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
49 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
50 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
51 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableRicConfig;
52 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableWebClientConfig;
53 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
54 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
55 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
66 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
67 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
68 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
69 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
70 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import org.springframework.beans.factory.annotation.Autowired;
74 import org.springframework.boot.test.context.SpringBootTest;
75 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
76 import org.springframework.boot.test.context.TestConfiguration;
77 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
78 import org.springframework.boot.web.server.LocalServerPort;
79 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
80 import org.springframework.context.ApplicationContext;
81 import org.springframework.context.annotation.Bean;
82 import org.springframework.http.HttpStatus;
83 import org.springframework.http.MediaType;
84 import org.springframework.http.ResponseEntity;
85 import org.springframework.test.context.TestPropertySource;
86 import org.springframework.test.context.junit.jupiter.SpringExtension;
87 import org.springframework.web.reactive.function.client.WebClientResponseException;
89 import reactor.core.publisher.Mono;
90 import reactor.test.StepVerifier;
91 import reactor.util.annotation.Nullable;
93 @ExtendWith(SpringExtension.class)
94 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
95 @TestPropertySource(properties = { //
96 "server.ssl.key-store=./config/keystore.jks", //
97 "app.webclient.trust-store=./config/truststore.jks"})
98 class ApplicationTest {
99 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
102 ApplicationContext context;
108 private Policies policies;
111 private PolicyTypes policyTypes;
114 MockA1ClientFactory a1ClientFactory;
117 RicSupervision supervision;
120 ApplicationConfig applicationConfig;
125 private static Gson gson = new GsonBuilder().create();
127 public static class MockApplicationConfig extends ApplicationConfig {
129 public String getLocalConfigurationFilePath() {
130 return ""; // No config file loaded for the test
135 * Overrides the BeanFactory.
138 static class TestBeanFactory {
139 private final PolicyTypes policyTypes = new PolicyTypes();
140 private final Services services = new Services();
141 private final Policies policies = new Policies();
142 MockA1ClientFactory a1ClientFactory = null;
145 public ApplicationConfig getApplicationConfig() {
146 return new MockApplicationConfig();
150 MockA1ClientFactory getA1ClientFactory() {
151 if (a1ClientFactory == null) {
152 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
154 return this.a1ClientFactory;
158 public PolicyTypes getPolicyTypes() {
159 return this.policyTypes;
163 Policies getPolicies() {
164 return this.policies;
168 Services getServices() {
169 return this.services;
173 public ServiceSupervision getServiceSupervision() {
174 Duration checkInterval = Duration.ofMillis(1);
175 return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
179 public ServletWebServerFactory servletContainer() {
180 return new TomcatServletWebServerFactory();
194 a1ClientFactory.reset();
198 void verifyNoRicLocks() {
199 for (Ric ric : this.rics.getRics()) {
200 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
201 ric.getLock().unlockBlocking();
202 assertThat(ric.getLock().getLockCounter()).isZero();
203 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
208 void createApiDoc() throws FileNotFoundException {
209 String url = "https://localhost:" + this.port + "/v2/api-docs";
210 ResponseEntity<String> resp = restClient("", false).getForEntity(url).block();
211 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
212 String indented = (new JSONObject(resp.getBody())).toString(4);
213 try (PrintStream out = new PrintStream(new FileOutputStream("../docs/offeredapis/swagger/pms-api.json"))) {
219 void testGetRics() throws Exception {
221 this.addPolicyType("type1", "ric1");
222 String url = "/rics?policytype_id=type1";
223 String rsp = restClient().get(url).block();
224 assertThat(rsp).contains("ric1");
226 // nameless type for ORAN A1 1.1
228 this.addPolicyType("", "ric2");
229 url = "/rics?policytype_id=";
231 // This tests also validation of trusted certs restClient(true)
232 rsp = restClient(true).get(url).block();
233 assertThat(rsp).contains("ric2") //
234 .doesNotContain("ric1") //
235 .contains("AVAILABLE");
238 rsp = restClient().get("/rics").block();
239 assertThat(rsp).contains("ric2") //
242 // Non existing policy type
243 url = "/rics?policytype_id=XXXX";
244 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
248 void testSynchronization() throws Exception {
249 // Two polictypes will be put in the NearRT RICs
250 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
251 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
252 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
253 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
255 // One type and one instance added to the Policy Management Service's storage
256 final String ric1Name = "ric1";
257 Ric ric1 = addRic(ric1Name);
258 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
259 Ric ric2 = addRic("ric2");
261 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
262 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
264 String policyId = "policyId";
265 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
266 supervision.checkAllRics(); // The created policy should be put in the RIC
268 // Wait until synch is completed
269 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
270 waitForRicState(ric1Name, RicState.AVAILABLE);
271 waitForRicState("ric2", RicState.AVAILABLE);
273 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
274 assertThat(ricPolicies.size()).isEqualTo(1);
275 Policy ricPolicy = ricPolicies.get(policyId);
276 assertThat(ricPolicy.json()).isEqualTo(policy.json());
278 // Both types should be in the Policy Management Service's storage after the
280 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
281 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
285 void testGetRic() throws Exception {
286 String ricId = "ric1";
287 String managedElementId = "kista_1";
288 addRic(ricId, managedElementId);
290 String url = "/rics/ric?managed_element_id=" + managedElementId;
291 String rsp = restClient().get(url).block();
292 RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
293 assertThat(ricInfo.ricId).isEqualTo(ricId);
295 url = "/rics/ric?ric_id=" + ricId;
296 rsp = restClient().get(url).block();
297 ricInfo = gson.fromJson(rsp, RicInfo.class);
298 assertThat(ricInfo.ricId).isEqualTo(ricId);
300 // test GET RIC for ManagedElement that does not exist
301 url = "/rics/ric?managed_element_id=" + "junk";
302 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
305 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
308 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
309 boolean isTransient) {
310 PolicyInfo info = new PolicyInfo();
311 info.policyId = policyInstanceId;
312 info.policyTypeId = policyTypeName;
314 info.serviceId = serviceName;
315 info.policyData = gson.fromJson(jsonString(), Object.class);
318 info.isTransient = isTransient;
320 info.statusNotificationUri = "statusNotificationUri";
321 return gson.toJson(info);
324 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
325 return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false);
329 void testPutPolicy() throws Exception {
330 String serviceName = "service1";
331 String ricId = "ric1";
332 String policyTypeName = "type1";
333 String policyInstanceId = "instance1";
335 putService(serviceName);
336 addPolicyType(policyTypeName, ricId);
338 // PUT a transient policy
339 String url = "/policies";
340 String policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, true);
341 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
343 restClient().put(url, policyBody).block();
345 Policy policy = policies.getPolicy(policyInstanceId);
346 assertThat(policy).isNotNull();
347 assertThat(policy.id()).isEqualTo(policyInstanceId);
348 assertThat(policy.ownerServiceId()).isEqualTo(serviceName);
349 assertThat(policy.ric().id()).isEqualTo("ric1");
350 assertThat(policy.isTransient()).isTrue();
352 // Put a non transient policy
353 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
354 restClient().put(url, policyBody).block();
355 policy = policies.getPolicy(policyInstanceId);
356 assertThat(policy.isTransient()).isFalse();
358 url = "/policy_instances";
359 String rsp = restClient().get(url).block();
360 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
362 url = "/policies/" + policyInstanceId;
363 rsp = restClient().get(url).block();
364 assertThat(rsp).contains(policyBody);
366 // Test of error codes
368 policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
369 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
371 policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
372 addPolicyType(policyTypeName + "XX", "otherRic");
373 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
375 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
376 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
377 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
378 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
383 * Test that HttpStatus and body from failing REST call to A1 is passed on to
386 * @throws ServiceException
388 void testErrorFromRic() throws ServiceException {
389 putService("service1");
390 addPolicyType("type1", "ric1");
392 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
393 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
394 String responseBody = "Refused";
395 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
397 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
398 responseBodyBytes, StandardCharsets.UTF_8, null);
399 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
402 String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
403 String url = "/policies";
404 testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
407 this.addPolicy("instance1", "type1", "service1", "ric1");
408 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
409 testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
414 void testPutTypelessPolicy() throws Exception {
415 putService("service1");
416 addPolicyType("", "ric1");
417 String body = putPolicyBody("service1", "ric1", "", "id1");
418 restClient().put("/policies", body).block();
420 String rsp = restClient().get("/policy_instances").block();
421 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
422 assertThat(info.policies).hasSize(1);
423 PolicyInfo policyInfo = info.policies.iterator().next();
424 assertThat(policyInfo.policyId).isEqualTo("id1");
425 assertThat(policyInfo.policyTypeId).isEmpty();
429 void testRefuseToUpdatePolicy() throws Exception {
430 // Test that only the json can be changed for a already created policy
431 // In this case service is attempted to be changed
433 this.addRic("ricXXX");
434 this.addPolicy("instance1", "type1", "service1", "ric1");
435 this.addPolicy("instance2", "type1", "service1", "ricXXX");
437 // Try change ric1 -> ricXXX
438 String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
439 testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
443 void testGetPolicy() throws Exception {
444 String url = "/policies/id";
445 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
447 String rsp = restClient().get(url).block();
448 PolicyInfo info = gson.fromJson(rsp, PolicyInfo.class);
449 String policyStr = gson.toJson(info.policyData);
450 assertThat(policyStr).isEqualTo(policy.json());
453 policies.remove(policy);
454 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
459 void testDeletePolicy() throws Exception {
460 addPolicy("id", "typeName", "service1", "ric1");
461 assertThat(policies.size()).isEqualTo(1);
463 String url = "/policies/id";
464 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
466 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
467 assertThat(policies.size()).isZero();
469 // Delete a non existing policy
470 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
474 void testGetPolicyType() throws Exception {
475 addPolicyType("type1", "ric1");
477 waitForRicState("ric1", RicState.AVAILABLE);
479 String url = "/policy-types/type1";
480 String rsp = this.restClient().get(url).block();
482 PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
483 assertThat(info.schema).isNotNull();
485 // Get non existing schema
486 url = "/policy-types/JUNK";
487 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
490 String createPolicyTypesJson(String... types) {
491 List<String> list = new ArrayList<>();
492 Collections.addAll(list, types);
493 PolicyTypeIdList ids = new PolicyTypeIdList(list);
494 return gson.toJson(ids);
498 void testGetPolicyTypes() throws Exception {
499 addPolicyType("type1", "ric1");
500 addPolicyType("type2", "ric2");
502 String url = "/policy-types";
503 String rsp = restClient().get(url).block();
504 String expResp = createPolicyTypesJson("type2", "type1");
505 assertThat(rsp).isEqualTo(expResp);
507 url = "/policy-types?ric_id=ric1";
508 rsp = restClient().get(url).block();
509 expResp = createPolicyTypesJson("type1");
510 assertThat(rsp).isEqualTo(expResp);
512 // Get policy types for non existing RIC
513 url = "/policy-types?ric_id=ric1XXX";
514 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
518 void testGetPolicyInstances() throws Exception {
519 addPolicy("id1", "type1", "service1");
521 String url = "/policy_instances";
522 String rsp = restClient().get(url).block();
524 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
525 assertThat(info.policies).hasSize(1);
526 PolicyInfo policyInfo = info.policies.iterator().next();
527 assert (policyInfo.validate());
528 assertThat(policyInfo.policyId).isEqualTo("id1");
529 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
530 assertThat(policyInfo.serviceId).isEqualTo("service1");
534 void testGetPolicyInstancesFilter() throws Exception {
535 addPolicy("id1", "type1", "service1");
536 addPolicy("id2", "type1", "service2");
537 addPolicy("id3", "type2", "service1");
539 String url = "/policy_instances?policytype_id=type1";
540 String rsp = restClient().get(url).block();
542 assertThat(rsp).contains("id1") //
544 .doesNotContain("id3");
546 url = "/policy_instances?policytype_id=type1&service_id=service2";
547 rsp = restClient().get(url).block();
549 assertThat(rsp).doesNotContain("id1") //
551 .doesNotContain("id3");
553 // Test get policies for non existing type
554 url = "/policy_instances?policytype_id=type1XXX";
555 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
557 // Test get policies for non existing RIC
558 url = "/policy_instances?ric_id=XXX";
559 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
563 void testGetPolicyIdsFilter() throws Exception {
564 addPolicy("id1", "type1", "service1", "ric1");
565 addPolicy("id2", "type1", "service2", "ric1");
566 addPolicy("id3", "type2", "service1", "ric1");
568 String url = "/policies?policytype_id=type1";
569 String rsp = restClient().get(url).block();
571 assertThat(rsp).contains("id1") //
573 .doesNotContain("id3");
575 url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
576 rsp = restClient().get(url).block();
577 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
578 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
580 // Test get policy ids for non existing type
581 url = "/policies?policytype_id=type1XXX";
582 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
584 // Test get policy ids for non existing RIC
585 url = "/policies?ric_id=XXX";
586 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
590 void testPutAndGetService() throws Exception {
592 String serviceName = "name";
593 putService(serviceName, 0, HttpStatus.CREATED);
594 putService(serviceName, 0, HttpStatus.OK);
597 String url = "/services?service_id=name";
598 String rsp = restClient().get(url).block();
599 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
600 assertThat(info.statusList).hasSize(1);
601 ServiceStatus status = info.statusList.iterator().next();
602 assertThat(status.keepAliveIntervalSeconds).isZero();
603 assertThat(status.serviceId).isEqualTo(serviceName);
607 rsp = restClient().get(url).block();
608 assertThat(rsp).as("Response contains service name").contains(serviceName);
612 url = "/services/name/keepalive";
613 ResponseEntity<?> entity = restClient().putForEntity(url).block();
614 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
617 assertThat(services.size()).isEqualTo(1);
618 url = "/services/name";
619 restClient().delete(url).block();
620 assertThat(services.size()).isZero();
622 // Keep alive, no registered service
623 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
625 // PUT service with bad payload
626 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
627 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
628 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
630 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
631 HttpStatus.BAD_REQUEST, false);
633 // GET non existing service
634 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
638 void testServiceSupervision() throws Exception {
639 putService("service1", 1, HttpStatus.CREATED);
640 addPolicyType("type1", "ric1");
642 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
643 restClient().put("/policies", policyBody).block();
645 assertThat(policies.size()).isEqualTo(1);
646 assertThat(services.size()).isEqualTo(1);
648 // Timeout after ~1 second
649 await().untilAsserted(() -> assertThat(policies.size()).isZero());
650 assertThat(services.size()).isZero();
654 void testGetPolicyStatus() throws Exception {
655 addPolicy("id", "typeName", "service1", "ric1");
656 assertThat(policies.size()).isEqualTo(1);
658 String url = "/policies/id/status";
659 String rsp = restClient().get(url).block();
660 PolicyStatusInfo info = gson.fromJson(rsp, PolicyStatusInfo.class);
661 assertThat(info.status).isEqualTo("OK");
663 // GET non existing policy status
664 url = "/policies/XXX/status";
665 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
667 // GET STATUS, the NearRT RIC returns error
668 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
669 url = "/policies/id/status";
670 WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
671 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
672 rsp = restClient().get(url).block();
673 info = gson.fromJson(rsp, PolicyStatusInfo.class);
674 assertThat(info.status.toString()).isEqualTo("{}");
678 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
680 Policy policy = ImmutablePolicy.builder() //
682 .json(jsonString()) //
683 .ownerServiceId(service) //
684 .ric(rics.getRic(ric)) //
685 .type(addPolicyType(typeName, ric)) //
686 .lastModified(Instant.now()) //
687 .isTransient(false) //
688 .statusNotificationUri("/policy_status?id=XXX") //
690 policies.put(policy);
694 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
695 return addPolicy(id, typeName, service, "ric");
698 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
699 return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
702 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
703 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
705 String json = gson.toJson(service);
709 private void putService(String name) {
710 putService(name, 0, null);
713 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
714 String url = "/services";
715 String body = createServiceJson(name, keepAliveIntervalSeconds);
716 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
717 if (expectedStatus != null) {
718 assertEquals(expectedStatus, resp.getStatusCode(), "");
722 private String jsonString() {
723 return "{\"servingCellNrcgi\":\"1\"}";
727 void testConcurrency() throws Exception {
728 final Instant startTime = Instant.now();
729 List<Thread> threads = new ArrayList<>();
730 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
731 a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
733 addPolicyType("type1", "ric");
734 addPolicyType("type2", "ric");
736 for (int i = 0; i < 10; ++i) {
737 AsyncRestClient restClient = restClient();
738 ConcurrencyTestRunnable test =
739 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
740 Thread thread = new Thread(test, "TestThread_" + i);
745 for (Thread t : threads) {
748 for (ConcurrencyTestRunnable test : tests) {
749 assertThat(test.isFailed()).isFalse();
751 assertThat(policies.size()).isZero();
752 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
755 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
756 WebClientConfig config = this.applicationConfig.getWebClientConfig();
757 config = ImmutableWebClientConfig.builder() //
758 .keyStoreType(config.keyStoreType()) //
759 .keyStorePassword(config.keyStorePassword()) //
760 .keyStore(config.keyStore()) //
761 .keyPassword(config.keyPassword()) //
762 .isTrustStoreUsed(useTrustValidation) //
763 .trustStore(config.trustStore()) //
764 .trustStorePassword(config.trustStorePassword()) //
767 AsyncRestClientFactory f = new AsyncRestClientFactory(config);
768 return f.createRestClient(baseUrl);
772 private AsyncRestClient restClient(boolean useTrustValidation) {
773 String baseUrl = "https://localhost:" + port + Consts.V2_API_ROOT;
774 return restClient(baseUrl, useTrustValidation);
777 private AsyncRestClient restClient() {
778 return restClient(false);
781 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
782 testErrorCode(request, expStatus, "", true);
785 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
786 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
789 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
790 testErrorCode(request, expStatus, responseContains, true);
793 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
794 boolean expectApplicationProblemJsonMediaType) {
795 StepVerifier.create(request) //
796 .expectSubscription() //
798 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
802 private void waitForRicState(String ricId, RicState state) throws ServiceException {
803 Ric ric = rics.getRic(ricId);
804 await().untilAsserted(() -> state.equals(ric.getState()));
807 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
808 boolean expectApplicationProblemJsonMediaType) {
809 assertTrue(throwable instanceof WebClientResponseException);
810 WebClientResponseException responseException = (WebClientResponseException) throwable;
811 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
812 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
813 if (expectApplicationProblemJsonMediaType) {
814 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
819 private MockA1Client getA1Client(String ricId) throws ServiceException {
820 return a1ClientFactory.getOrCreateA1Client(ricId);
823 private PolicyType createPolicyType(String policyTypeName) {
824 return ImmutablePolicyType.builder() //
825 .id(policyTypeName) //
826 .schema("{\"title\":\"" + policyTypeName + "\"}") //
830 private PolicyType addPolicyType(String policyTypeName, String ricId) {
831 PolicyType type = createPolicyType(policyTypeName);
832 policyTypes.put(type);
833 addRic(ricId).addSupportedPolicyType(type);
837 private Ric addRic(String ricId) {
838 return addRic(ricId, null);
841 private Ric addRic(String ricId, String managedElement) {
842 if (rics.get(ricId) != null) {
843 return rics.get(ricId);
845 List<String> mes = new ArrayList<>();
846 if (managedElement != null) {
847 mes.add(managedElement);
849 RicConfig conf = ImmutableRicConfig.builder() //
852 .managedElementIds(mes) //
853 .controllerName("") //
855 Ric ric = new Ric(conf);
856 ric.setState(Ric.RicState.AVAILABLE);