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 = "service1";
337 String ricId = "ric1";
338 String policyTypeName = "type1";
339 String policyInstanceId = "instance1";
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("ric1");
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 addPolicy("id", "typeName", "service1", "ric1");
467 assertThat(policies.size()).isEqualTo(1);
469 String url = "/policies/id";
470 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
472 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
473 assertThat(policies.size()).isZero();
475 // Delete a non existing policy
476 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
480 void testGetPolicyType() throws Exception {
481 addPolicyType("type1", "ric1");
483 waitForRicState("ric1", RicState.AVAILABLE);
485 String url = "/policy-types/type1";
486 String rsp = this.restClient().get(url).block();
488 PolicyTypeInfo info = gson.fromJson(rsp, PolicyTypeInfo.class);
489 assertThat(info.schema).isNotNull();
491 // Get non existing schema
492 url = "/policy-types/JUNK";
493 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
496 String createPolicyTypesJson(String... types) {
497 List<String> list = new ArrayList<>();
498 Collections.addAll(list, types);
499 PolicyTypeIdList ids = new PolicyTypeIdList(list);
500 return gson.toJson(ids);
504 void testGetPolicyTypes() throws Exception {
505 addPolicyType("type1", "ric1");
506 addPolicyType("type2", "ric2");
508 String url = "/policy-types";
509 String rsp = restClient().get(url).block();
510 String expResp = createPolicyTypesJson("type2", "type1");
511 assertThat(rsp).isEqualTo(expResp);
513 url = "/policy-types?ric_id=ric1";
514 rsp = restClient().get(url).block();
515 expResp = createPolicyTypesJson("type1");
516 assertThat(rsp).isEqualTo(expResp);
518 // Get policy types for non existing RIC
519 url = "/policy-types?ric_id=ric1XXX";
520 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
524 void testGetPolicyInstances() throws Exception {
525 addPolicy("id1", "type1", "service1");
527 String url = "/policy-instances";
528 String rsp = restClient().get(url).block();
530 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
531 assertThat(info.policies).hasSize(1);
532 PolicyInfo policyInfo = info.policies.iterator().next();
533 assert (policyInfo.validate());
534 assertThat(policyInfo.policyId).isEqualTo("id1");
535 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
536 assertThat(policyInfo.serviceId).isEqualTo("service1");
540 void testGetPolicyInstancesFilter() throws Exception {
541 addPolicy("id1", "type1", "service1");
542 addPolicy("id2", "type1", "service2");
543 addPolicy("id3", "type2", "service1");
545 String url = "/policy-instances?policytype_id=type1";
546 String rsp = restClient().get(url).block();
548 assertThat(rsp).contains("id1") //
550 .doesNotContain("id3");
552 url = "/policy-instances?policytype_id=type1&service_id=service2";
553 rsp = restClient().get(url).block();
555 assertThat(rsp).doesNotContain("id1") //
557 .doesNotContain("id3");
559 // Test get policies for non existing type
560 url = "/policy-instances?policytype_id=type1XXX";
561 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
563 // Test get policies for non existing RIC
564 url = "/policy-instances?ric_id=XXX";
565 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
569 void testGetPolicyIdsFilter() throws Exception {
570 addPolicy("id1", "type1", "service1", "ric1");
571 addPolicy("id2", "type1", "service2", "ric1");
572 addPolicy("id3", "type2", "service1", "ric1");
574 String url = "/policies?policytype_id=type1";
575 String rsp = restClient().get(url).block();
577 assertThat(rsp).contains("id1") //
579 .doesNotContain("id3");
581 url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
582 rsp = restClient().get(url).block();
583 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
584 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
586 // Test get policy ids for non existing type
587 url = "/policies?policytype_id=type1XXX";
588 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
590 // Test get policy ids for non existing RIC
591 url = "/policies?ric_id=XXX";
592 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
596 void testPutAndGetService() throws Exception {
598 String serviceName = "name";
599 putService(serviceName, 0, HttpStatus.CREATED);
600 putService(serviceName, 0, HttpStatus.OK);
603 String url = "/services?service_id=name";
604 String rsp = restClient().get(url).block();
605 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
606 assertThat(info.statusList).hasSize(1);
607 ServiceStatus status = info.statusList.iterator().next();
608 assertThat(status.keepAliveIntervalSeconds).isZero();
609 assertThat(status.serviceId).isEqualTo(serviceName);
613 rsp = restClient().get(url).block();
614 assertThat(rsp).as("Response contains service name").contains(serviceName);
618 url = "/services/name/keepalive";
619 ResponseEntity<?> entity = restClient().putForEntity(url).block();
620 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
623 assertThat(services.size()).isEqualTo(1);
624 url = "/services/name";
625 restClient().delete(url).block();
626 assertThat(services.size()).isZero();
628 // Keep alive, no registered service
629 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
631 // PUT service with bad payload
632 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
633 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
634 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
636 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
637 HttpStatus.BAD_REQUEST, false);
639 // GET non existing service
640 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
644 void testServiceSupervision() throws Exception {
645 putService("service1", 1, HttpStatus.CREATED);
646 addPolicyType("type1", "ric1");
648 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
649 restClient().put("/policies", policyBody).block();
651 assertThat(policies.size()).isEqualTo(1);
652 assertThat(services.size()).isEqualTo(1);
654 // Timeout after ~1 second
655 await().untilAsserted(() -> assertThat(policies.size()).isZero());
656 assertThat(services.size()).isZero();
660 void testGetPolicyStatus() throws Exception {
661 addPolicy("id", "typeName", "service1", "ric1");
662 assertThat(policies.size()).isEqualTo(1);
664 String url = "/policies/id/status";
665 String rsp = restClient().get(url).block();
666 PolicyStatusInfo info = gson.fromJson(rsp, PolicyStatusInfo.class);
667 assertThat(info.status).isEqualTo("OK");
669 // GET non existing policy status
670 url = "/policies/XXX/status";
671 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
673 // GET STATUS, the NearRT RIC returns error
674 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
675 url = "/policies/id/status";
676 WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
677 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
678 rsp = restClient().get(url).block();
679 info = gson.fromJson(rsp, PolicyStatusInfo.class);
680 assertThat(info.status.toString()).isEqualTo("{}");
684 void testServiceNotification() throws ServiceException {
685 putService("junkService");
686 Service junkService = this.services.get("junkService");
687 junkService.setCallbackUrl("https://junk");
688 putService("service");
690 Ric ric = addRic("ric1");
691 ric.setState(Ric.RicState.UNAVAILABLE);
692 supervision.checkAllRics();
693 waitForRicState("ric1", RicState.AVAILABLE);
695 RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
696 assertThat(receivedCallbacks.getReceivedInfo().size()).isEqualTo(1);
697 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
698 assertThat(callbackInfo.ricId).isEqualTo("ric1");
699 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
702 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
704 Policy policy = ImmutablePolicy.builder() //
706 .json(jsonString()) //
707 .ownerServiceId(service) //
708 .ric(rics.getRic(ric)) //
709 .type(addPolicyType(typeName, ric)) //
710 .lastModified(Instant.now()) //
711 .isTransient(false) //
712 .statusNotificationUri("/policy-status?id=XXX") //
714 policies.put(policy);
718 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
719 return addPolicy(id, typeName, service, "ric");
722 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
723 String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
724 return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
727 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
728 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
730 String json = gson.toJson(service);
734 private void putService(String name) {
735 putService(name, 0, null);
738 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
739 String url = "/services";
740 String body = createServiceJson(name, keepAliveIntervalSeconds);
741 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
742 if (expectedStatus != null) {
743 assertEquals(expectedStatus, resp.getStatusCode(), "");
747 private String jsonString() {
748 return "{\"servingCellNrcgi\":\"1\"}";
752 void testConcurrency() throws Exception {
753 final Instant startTime = Instant.now();
754 List<Thread> threads = new ArrayList<>();
755 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
756 a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
758 addPolicyType("type1", "ric");
759 addPolicyType("type2", "ric");
761 for (int i = 0; i < 10; ++i) {
762 AsyncRestClient restClient = restClient();
763 ConcurrencyTestRunnable test =
764 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
765 Thread thread = new Thread(test, "TestThread_" + i);
770 for (Thread t : threads) {
773 for (ConcurrencyTestRunnable test : tests) {
774 assertThat(test.isFailed()).isFalse();
776 assertThat(policies.size()).isZero();
777 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
780 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
781 WebClientConfig config = this.applicationConfig.getWebClientConfig();
782 config = ImmutableWebClientConfig.builder() //
783 .keyStoreType(config.keyStoreType()) //
784 .keyStorePassword(config.keyStorePassword()) //
785 .keyStore(config.keyStore()) //
786 .keyPassword(config.keyPassword()) //
787 .isTrustStoreUsed(useTrustValidation) //
788 .trustStore(config.trustStore()) //
789 .trustStorePassword(config.trustStorePassword()) //
792 AsyncRestClientFactory f = new AsyncRestClientFactory(config);
793 return f.createRestClient(baseUrl);
797 private String baseUrl() {
798 return "https://localhost:" + port;
801 private AsyncRestClient restClient(boolean useTrustValidation) {
802 String baseUrl = "https://localhost:" + port + Consts.V2_API_ROOT;
803 return restClient(baseUrl, useTrustValidation);
806 private AsyncRestClient restClient() {
807 return restClient(false);
810 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
811 testErrorCode(request, expStatus, "", true);
814 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
815 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
818 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
819 testErrorCode(request, expStatus, responseContains, true);
822 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
823 boolean expectApplicationProblemJsonMediaType) {
824 StepVerifier.create(request) //
825 .expectSubscription() //
827 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
831 private void waitForRicState(String ricId, RicState state) throws ServiceException {
832 Ric ric = rics.getRic(ricId);
833 await().untilAsserted(() -> state.equals(ric.getState()));
836 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
837 boolean expectApplicationProblemJsonMediaType) {
838 assertTrue(throwable instanceof WebClientResponseException);
839 WebClientResponseException responseException = (WebClientResponseException) throwable;
840 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
841 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
842 if (expectApplicationProblemJsonMediaType) {
843 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
848 private MockA1Client getA1Client(String ricId) throws ServiceException {
849 return a1ClientFactory.getOrCreateA1Client(ricId);
852 private PolicyType createPolicyType(String policyTypeName) {
853 return ImmutablePolicyType.builder() //
854 .id(policyTypeName) //
855 .schema("{\"title\":\"" + policyTypeName + "\"}") //
859 private PolicyType addPolicyType(String policyTypeName, String ricId) {
860 PolicyType type = createPolicyType(policyTypeName);
861 policyTypes.put(type);
862 addRic(ricId).addSupportedPolicyType(type);
866 private Ric addRic(String ricId) {
867 return addRic(ricId, null);
870 private Ric addRic(String ricId, String managedElement) {
871 if (rics.get(ricId) != null) {
872 return rics.get(ricId);
874 List<String> mes = new ArrayList<>();
875 if (managedElement != null) {
876 mes.add(managedElement);
878 RicConfig conf = ImmutableRicConfig.builder() //
881 .managedElementIds(mes) //
882 .controllerName("") //
884 Ric ric = new Ric(conf);
885 ric.setState(Ric.RicState.AVAILABLE);