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.controllers.ServiceCallbackInfo;
56 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
66 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
67 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
68 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
69 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
70 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
71 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
72 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.springframework.beans.factory.annotation.Autowired;
76 import org.springframework.boot.test.context.SpringBootTest;
77 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
78 import org.springframework.boot.test.context.TestConfiguration;
79 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
80 import org.springframework.boot.web.server.LocalServerPort;
81 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
82 import org.springframework.context.ApplicationContext;
83 import org.springframework.context.annotation.Bean;
84 import org.springframework.http.HttpStatus;
85 import org.springframework.http.MediaType;
86 import org.springframework.http.ResponseEntity;
87 import org.springframework.test.context.TestPropertySource;
88 import org.springframework.test.context.junit.jupiter.SpringExtension;
89 import org.springframework.web.reactive.function.client.WebClientResponseException;
91 import reactor.core.publisher.Mono;
92 import reactor.test.StepVerifier;
93 import reactor.util.annotation.Nullable;
95 @ExtendWith(SpringExtension.class)
96 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
97 @TestPropertySource(properties = { //
98 "server.ssl.key-store=./config/keystore.jks", //
99 "app.webclient.trust-store=./config/truststore.jks"})
100 class ApplicationTest {
101 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
104 ApplicationContext context;
110 private Policies policies;
113 private PolicyTypes policyTypes;
116 MockA1ClientFactory a1ClientFactory;
119 RicSupervision supervision;
122 ApplicationConfig applicationConfig;
128 RappSimulatorController rAppSimulator;
130 private static Gson gson = new GsonBuilder().create();
132 public static class MockApplicationConfig extends ApplicationConfig {
134 public String getLocalConfigurationFilePath() {
135 return ""; // No config file loaded for the test
140 * Overrides the BeanFactory.
143 static class TestBeanFactory {
144 private final PolicyTypes policyTypes = new PolicyTypes();
145 private final Services services = new Services();
146 private final Policies policies = new Policies();
147 MockA1ClientFactory a1ClientFactory = null;
150 public ApplicationConfig getApplicationConfig() {
151 return new MockApplicationConfig();
155 MockA1ClientFactory getA1ClientFactory() {
156 if (a1ClientFactory == null) {
157 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
159 return this.a1ClientFactory;
163 public PolicyTypes getPolicyTypes() {
164 return this.policyTypes;
168 Policies getPolicies() {
169 return this.policies;
173 Services getServices() {
174 return this.services;
178 public ServiceSupervision getServiceSupervision() {
179 Duration checkInterval = Duration.ofMillis(1);
180 return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
184 public ServletWebServerFactory servletContainer() {
185 return new TomcatServletWebServerFactory();
199 a1ClientFactory.reset();
200 this.rAppSimulator.getTestResults().clear();
204 void verifyNoRicLocks() {
205 for (Ric ric : this.rics.getRics()) {
206 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
207 ric.getLock().unlockBlocking();
208 assertThat(ric.getLock().getLockCounter()).isZero();
209 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
214 void createApiDoc() throws FileNotFoundException {
215 String url = "https://localhost:" + this.port + "/v2/api-docs";
216 ResponseEntity<String> resp = restClient("", false).getForEntity(url).block();
217 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
218 String indented = (new JSONObject(resp.getBody())).toString(4);
219 try (PrintStream out = new PrintStream(new FileOutputStream("../docs/offeredapis/swagger/pms-api.json"))) {
225 void testGetRics() throws Exception {
227 this.addPolicyType("type1", "ric1");
228 String url = "/rics?policytype_id=type1";
229 String rsp = restClient().get(url).block();
230 assertThat(rsp).contains("ric1");
232 // nameless type for ORAN A1 1.1
234 this.addPolicyType("", "ric2");
235 url = "/rics?policytype_id=";
237 // This tests also validation of trusted certs restClient(true)
238 rsp = restClient(true).get(url).block();
239 assertThat(rsp).contains("ric2") //
240 .doesNotContain("ric1") //
241 .contains("AVAILABLE");
244 rsp = restClient().get("/rics").block();
245 assertThat(rsp).contains("ric2") //
248 // Non existing policy type
249 url = "/rics?policytype_id=XXXX";
250 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
254 void testSynchronization() throws Exception {
255 // Two polictypes will be put in the NearRT RICs
256 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
257 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
258 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
259 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
261 // One type and one instance added to the Policy Management Service's storage
262 final String ric1Name = "ric1";
263 Ric ric1 = addRic(ric1Name);
264 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
265 Ric ric2 = addRic("ric2");
267 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
268 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
270 String policyId = "policyId";
271 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
272 supervision.checkAllRics(); // The created policy should be put in the RIC
274 // Wait until synch is completed
275 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
276 waitForRicState(ric1Name, RicState.AVAILABLE);
277 waitForRicState("ric2", RicState.AVAILABLE);
279 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
280 assertThat(ricPolicies.size()).isEqualTo(1);
281 Policy ricPolicy = ricPolicies.get(policyId);
282 assertThat(ricPolicy.json()).isEqualTo(policy.json());
284 // Both types should be in the Policy Management Service's storage after the
286 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
287 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
291 void testGetRic() throws Exception {
292 String ricId = "ric1";
293 String managedElementId = "kista_1";
294 addRic(ricId, managedElementId);
296 String url = "/rics/ric?managed_element_id=" + managedElementId;
297 String rsp = restClient().get(url).block();
298 RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
299 assertThat(ricInfo.ricId).isEqualTo(ricId);
301 url = "/rics/ric?ric_id=" + ricId;
302 rsp = restClient().get(url).block();
303 ricInfo = gson.fromJson(rsp, RicInfo.class);
304 assertThat(ricInfo.ricId).isEqualTo(ricId);
306 // test GET RIC for ManagedElement that does not exist
307 url = "/rics/ric?managed_element_id=" + "junk";
308 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
311 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
314 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
315 boolean isTransient) {
316 PolicyInfo info = new PolicyInfo();
317 info.policyId = policyInstanceId;
318 info.policyTypeId = policyTypeName;
320 info.serviceId = serviceName;
321 info.policyData = gson.fromJson(jsonString(), Object.class);
324 info.isTransient = isTransient;
326 info.statusNotificationUri = "statusNotificationUri";
327 return gson.toJson(info);
330 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
331 return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false);
335 void testPutPolicy() throws Exception {
336 String serviceName = "service.1";
337 String ricId = "ric.1";
338 String policyTypeName = "type1_1.2.3";
339 String policyInstanceId = "instance_1.2.3";
341 putService(serviceName);
342 addPolicyType(policyTypeName, ricId);
344 // PUT a transient policy
345 String url = "/policies";
346 String policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, true);
347 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
349 restClient().put(url, policyBody).block();
351 Policy policy = policies.getPolicy(policyInstanceId);
352 assertThat(policy).isNotNull();
353 assertThat(policy.id()).isEqualTo(policyInstanceId);
354 assertThat(policy.ownerServiceId()).isEqualTo(serviceName);
355 assertThat(policy.ric().id()).isEqualTo(ricId);
356 assertThat(policy.isTransient()).isTrue();
358 // Put a non transient policy
359 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
360 restClient().put(url, policyBody).block();
361 policy = policies.getPolicy(policyInstanceId);
362 assertThat(policy.isTransient()).isFalse();
364 url = "/policy-instances";
365 String rsp = restClient().get(url).block();
366 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
368 url = "/policies/" + policyInstanceId;
369 rsp = restClient().get(url).block();
370 assertThat(rsp).contains(policyBody);
372 // Test of error codes
374 policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
375 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
377 policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
378 addPolicyType(policyTypeName + "XX", "otherRic");
379 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
381 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
382 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
383 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
384 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
389 * Test that HttpStatus and body from failing REST call to A1 is passed on to
392 * @throws ServiceException
394 void testErrorFromRic() throws ServiceException {
395 putService("service1");
396 addPolicyType("type1", "ric1");
398 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
399 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
400 String responseBody = "Refused";
401 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
403 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
404 responseBodyBytes, StandardCharsets.UTF_8, null);
405 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
408 String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
409 String url = "/policies";
410 testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
413 this.addPolicy("instance1", "type1", "service1", "ric1");
414 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
415 testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
420 void testPutTypelessPolicy() throws Exception {
421 putService("service1");
422 addPolicyType("", "ric1");
423 String body = putPolicyBody("service1", "ric1", "", "id1");
424 restClient().put("/policies", body).block();
426 String rsp = restClient().get("/policy-instances").block();
427 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
428 assertThat(info.policies).hasSize(1);
429 PolicyInfo policyInfo = info.policies.iterator().next();
430 assertThat(policyInfo.policyId).isEqualTo("id1");
431 assertThat(policyInfo.policyTypeId).isEmpty();
435 void testRefuseToUpdatePolicy() throws Exception {
436 // Test that only the json can be changed for a already created policy
437 // In this case service is attempted to be changed
439 this.addRic("ricXXX");
440 this.addPolicy("instance1", "type1", "service1", "ric1");
441 this.addPolicy("instance2", "type1", "service1", "ricXXX");
443 // Try change ric1 -> ricXXX
444 String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
445 testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
449 void testGetPolicy() throws Exception {
450 String url = "/policies/id";
451 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
453 String rsp = restClient().get(url).block();
454 PolicyInfo info = gson.fromJson(rsp, PolicyInfo.class);
455 String policyStr = gson.toJson(info.policyData);
456 assertThat(policyStr).isEqualTo(policy.json());
459 policies.remove(policy);
460 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
465 void testDeletePolicy() throws Exception {
466 String policyId = "id.1";
467 addPolicy(policyId, "typeName", "service1", "ric1");
468 assertThat(policies.size()).isEqualTo(1);
470 String url = "/policies/" + policyId;
471 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
473 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
474 assertThat(policies.size()).isZero();
476 // Delete a non existing policy
477 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
481 void testGetPolicyType() throws Exception {
482 String typeId = "AC.D";
483 addPolicyType(typeId, "ric1");
485 waitForRicState("ric1", RicState.AVAILABLE);
487 String url = "/policy-types/" + typeId;
489 String rsp = this.restClient().get(url).block();
491 PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
492 assertThat(info.schema).isNotNull();
494 // Get non existing schema
495 url = "/policy-types/JUNK";
496 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
499 String createPolicyTypesJson(String... types) {
500 List<String> list = new ArrayList<>();
501 Collections.addAll(list, types);
502 PolicyTypeIdList ids = new PolicyTypeIdList(list);
503 return gson.toJson(ids);
507 void testGetPolicyTypes() throws Exception {
508 addPolicyType("type1", "ric1");
509 addPolicyType("type2", "ric2");
511 String url = "/policy-types";
512 String rsp = restClient().get(url).block();
513 String expResp = createPolicyTypesJson("type2", "type1");
514 assertThat(rsp).isEqualTo(expResp);
516 url = "/policy-types?ric_id=ric1";
517 rsp = restClient().get(url).block();
518 expResp = createPolicyTypesJson("type1");
519 assertThat(rsp).isEqualTo(expResp);
521 // Get policy types for non existing RIC
522 url = "/policy-types?ric_id=ric1XXX";
523 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
527 void testGetPolicyInstances() throws Exception {
528 addPolicy("id1", "type1", "service1");
530 String url = "/policy-instances";
531 String rsp = restClient().get(url).block();
533 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
534 assertThat(info.policies).hasSize(1);
535 PolicyInfo policyInfo = info.policies.iterator().next();
536 assert (policyInfo.validate());
537 assertThat(policyInfo.policyId).isEqualTo("id1");
538 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
539 assertThat(policyInfo.serviceId).isEqualTo("service1");
543 void testGetPolicyInstancesFilter() throws Exception {
544 addPolicy("id1", "type1", "service1");
545 addPolicy("id2", "type1", "service2");
546 addPolicy("id3", "type2", "service1");
548 String url = "/policy-instances?policytype_id=type1";
549 String rsp = restClient().get(url).block();
551 assertThat(rsp).contains("id1") //
553 .doesNotContain("id3");
555 url = "/policy-instances?policytype_id=type1&service_id=service2";
556 rsp = restClient().get(url).block();
558 assertThat(rsp).doesNotContain("id1") //
560 .doesNotContain("id3");
562 // Test get policies for non existing type
563 url = "/policy-instances?policytype_id=type1XXX";
564 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
566 // Test get policies for non existing RIC
567 url = "/policy-instances?ric_id=XXX";
568 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
572 void testGetPolicyIdsFilter() throws Exception {
573 addPolicy("id1", "type1", "service1", "ric1");
574 addPolicy("id2", "type1", "service2", "ric1");
575 addPolicy("id3", "type2", "service1", "ric1");
577 String url = "/policies?policytype_id=type1";
578 String rsp = restClient().get(url).block();
580 assertThat(rsp).contains("id1") //
582 .doesNotContain("id3");
584 url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
585 rsp = restClient().get(url).block();
586 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
587 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
589 // Test get policy ids for non existing type
590 url = "/policies?policytype_id=type1XXX";
591 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
593 // Test get policy ids for non existing RIC
594 url = "/policies?ric_id=XXX";
595 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
599 void testPutAndGetService() throws Exception {
601 String serviceName = "ac.dc";
602 putService(serviceName, 0, HttpStatus.CREATED);
603 putService(serviceName, 0, HttpStatus.OK);
606 String url = "/services?service_id=" + serviceName;
607 String rsp = restClient().get(url).block();
608 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
609 assertThat(info.statusList).hasSize(1);
610 ServiceStatus status = info.statusList.iterator().next();
611 assertThat(status.keepAliveIntervalSeconds).isZero();
612 assertThat(status.serviceId).isEqualTo(serviceName);
616 rsp = restClient().get(url).block();
617 assertThat(rsp).as("Response contains service name").contains(serviceName);
621 url = "/services/" + serviceName + "/keepalive";
622 ResponseEntity<?> entity = restClient().putForEntity(url).block();
623 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
626 assertThat(services.size()).isEqualTo(1);
627 url = "/services/" + serviceName;
628 restClient().delete(url).block();
629 assertThat(services.size()).isZero();
631 // Keep alive, no registered service
632 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
634 // PUT service with bad payload
635 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
636 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
637 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
639 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
640 HttpStatus.BAD_REQUEST, false);
642 // GET non existing service
643 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
647 void testServiceSupervision() throws Exception {
648 putService("service1", 1, HttpStatus.CREATED);
649 addPolicyType("type1", "ric1");
651 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
652 restClient().put("/policies", policyBody).block();
654 assertThat(policies.size()).isEqualTo(1);
655 assertThat(services.size()).isEqualTo(1);
657 // Timeout after ~1 second
658 await().untilAsserted(() -> assertThat(policies.size()).isZero());
659 assertThat(services.size()).isZero();
663 void testGetPolicyStatus() throws Exception {
664 addPolicy("id", "typeName", "service1", "ric1");
665 assertThat(policies.size()).isEqualTo(1);
667 String url = "/policies/id/status";
668 String rsp = restClient().get(url).block();
669 PolicyStatusInfo info = gson.fromJson(rsp, PolicyStatusInfo.class);
670 assertThat(info.status).isEqualTo("OK");
672 // GET non existing policy status
673 url = "/policies/XXX/status";
674 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
676 // GET STATUS, the NearRT RIC returns error
677 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
678 url = "/policies/id/status";
679 WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
680 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
681 rsp = restClient().get(url).block();
682 info = gson.fromJson(rsp, PolicyStatusInfo.class);
683 assertThat(info.status.toString()).isEqualTo("{}");
687 void testServiceNotification() throws ServiceException {
688 putService("junkService");
689 Service junkService = this.services.get("junkService");
690 junkService.setCallbackUrl("https://junk");
691 putService("service");
693 Ric ric = addRic("ric1");
694 ric.setState(Ric.RicState.UNAVAILABLE);
695 supervision.checkAllRics();
696 waitForRicState("ric1", RicState.AVAILABLE);
698 RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
699 assertThat(receivedCallbacks.getReceivedInfo().size()).isEqualTo(1);
700 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
701 assertThat(callbackInfo.ricId).isEqualTo("ric1");
702 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
705 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
707 Policy policy = ImmutablePolicy.builder() //
709 .json(jsonString()) //
710 .ownerServiceId(service) //
711 .ric(rics.getRic(ric)) //
712 .type(addPolicyType(typeName, ric)) //
713 .lastModified(Instant.now()) //
714 .isTransient(false) //
715 .statusNotificationUri("/policy-status?id=XXX") //
717 policies.put(policy);
721 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
722 return addPolicy(id, typeName, service, "ric");
725 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
726 String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
727 return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
730 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
731 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
733 String json = gson.toJson(service);
737 private void putService(String name) {
738 putService(name, 0, null);
741 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
742 String url = "/services";
743 String body = createServiceJson(name, keepAliveIntervalSeconds);
744 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
745 if (expectedStatus != null) {
746 assertEquals(expectedStatus, resp.getStatusCode(), "");
750 private String jsonString() {
751 return "{\"servingCellNrcgi\":\"1\"}";
755 void testConcurrency() throws Exception {
756 final Instant startTime = Instant.now();
757 List<Thread> threads = new ArrayList<>();
758 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
759 a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
761 addPolicyType("type1", "ric");
762 addPolicyType("type2", "ric");
764 for (int i = 0; i < 10; ++i) {
765 AsyncRestClient restClient = restClient();
766 ConcurrencyTestRunnable test =
767 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
768 Thread thread = new Thread(test, "TestThread_" + i);
773 for (Thread t : threads) {
776 for (ConcurrencyTestRunnable test : tests) {
777 assertThat(test.isFailed()).isFalse();
779 assertThat(policies.size()).isZero();
780 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
783 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
784 WebClientConfig config = this.applicationConfig.getWebClientConfig();
785 config = ImmutableWebClientConfig.builder() //
786 .keyStoreType(config.keyStoreType()) //
787 .keyStorePassword(config.keyStorePassword()) //
788 .keyStore(config.keyStore()) //
789 .keyPassword(config.keyPassword()) //
790 .isTrustStoreUsed(useTrustValidation) //
791 .trustStore(config.trustStore()) //
792 .trustStorePassword(config.trustStorePassword()) //
793 .httpProxyConfig(config.httpProxyConfig()) //
796 AsyncRestClientFactory f = new AsyncRestClientFactory(config);
797 return f.createRestClientNoHttpProxy(baseUrl);
801 private String baseUrl() {
802 return "https://localhost:" + port;
805 private AsyncRestClient restClient(boolean useTrustValidation) {
806 String baseUrl = "https://localhost:" + port + Consts.V2_API_ROOT;
807 return restClient(baseUrl, useTrustValidation);
810 private AsyncRestClient restClient() {
811 return restClient(false);
814 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
815 testErrorCode(request, expStatus, "", true);
818 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
819 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
822 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
823 testErrorCode(request, expStatus, responseContains, true);
826 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
827 boolean expectApplicationProblemJsonMediaType) {
828 StepVerifier.create(request) //
829 .expectSubscription() //
831 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
835 private void waitForRicState(String ricId, RicState state) throws ServiceException {
836 Ric ric = rics.getRic(ricId);
837 await().untilAsserted(() -> state.equals(ric.getState()));
840 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
841 boolean expectApplicationProblemJsonMediaType) {
842 assertTrue(throwable instanceof WebClientResponseException);
843 WebClientResponseException responseException = (WebClientResponseException) throwable;
844 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
845 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
846 if (expectApplicationProblemJsonMediaType) {
847 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
852 private MockA1Client getA1Client(String ricId) throws ServiceException {
853 return a1ClientFactory.getOrCreateA1Client(ricId);
856 private PolicyType createPolicyType(String policyTypeName) {
857 return ImmutablePolicyType.builder() //
858 .id(policyTypeName) //
859 .schema("{\"title\":\"" + policyTypeName + "\"}") //
863 private PolicyType addPolicyType(String policyTypeName, String ricId) {
864 PolicyType type = createPolicyType(policyTypeName);
865 policyTypes.put(type);
866 addRic(ricId).addSupportedPolicyType(type);
870 private Ric addRic(String ricId) {
871 return addRic(ricId, null);
874 private Ric addRic(String ricId, String managedElement) {
875 if (rics.get(ricId) != null) {
876 return rics.get(ricId);
878 List<String> mes = new ArrayList<>();
879 if (managedElement != null) {
880 mes.add(managedElement);
882 RicConfig conf = ImmutableRicConfig.builder() //
885 .managedElementIds(mes) //
886 .controllerName("") //
888 Ric ric = new Ric(conf);
889 ric.setState(Ric.RicState.AVAILABLE);