2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2023 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.*;
26 import static org.mockito.ArgumentMatchers.any;
27 import static org.mockito.Mockito.doReturn;
29 import com.fasterxml.jackson.core.JsonProcessingException;
30 import com.fasterxml.jackson.databind.ObjectMapper;
32 import java.lang.invoke.MethodHandles;
33 import java.nio.charset.StandardCharsets;
34 import java.nio.file.Files;
35 import java.nio.file.Path;
36 import java.time.Duration;
37 import java.time.Instant;
38 import java.util.ArrayList;
39 import java.util.Collections;
40 import java.util.List;
42 import java.util.HashMap;
44 import org.junit.jupiter.api.AfterAll;
45 import org.junit.jupiter.api.AfterEach;
46 import org.junit.jupiter.api.BeforeEach;
47 import org.junit.jupiter.api.DisplayName;
48 import org.junit.jupiter.api.MethodOrderer;
49 import org.junit.jupiter.api.Test;
50 import org.junit.jupiter.api.TestMethodOrder;
51 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1ClientFactory;
52 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
53 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClientFactory;
54 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SecurityContext;
55 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
56 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig.RicConfigUpdate;
57 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
58 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
59 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.OpenPolicyAgentSimulatorController;
60 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.ServiceCallbackInfo;
61 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest;
62 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.authorization.PolicyAuthorizationRequest.Input.AccessType;
63 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
64 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.RicInfo;
65 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyTypeIdList;
66 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfo;
67 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyInfoList;
68 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyIdList;
69 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.PolicyStatusInfo;
70 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceStatusList;
71 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceStatus;
72 import org.onap.ccsdk.oran.a1policymanagementservice.models.v2.ServiceRegistrationInfo;
73 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock;
74 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
75 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
76 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
77 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
78 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
79 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
80 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
81 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
82 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Service;
83 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
84 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RefreshConfigTask;
85 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
86 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
87 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
88 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
91 import org.springframework.beans.factory.annotation.Autowired;
92 import org.springframework.boot.test.context.SpringBootTest;
93 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
94 import org.springframework.boot.test.context.TestConfiguration;
95 import org.springframework.boot.test.web.server.LocalServerPort;
96 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
97 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
98 import org.springframework.context.ApplicationContext;
99 import org.springframework.context.annotation.Bean;
100 import org.springframework.http.HttpStatus;
101 import org.springframework.http.MediaType;
102 import org.springframework.http.ResponseEntity;
103 import org.springframework.test.context.TestPropertySource;
104 import org.springframework.util.FileSystemUtils;
105 import org.springframework.web.reactive.function.client.WebClientResponseException;
107 import reactor.core.publisher.Mono;
108 import reactor.test.StepVerifier;
109 import reactor.util.annotation.Nullable;
111 @TestMethodOrder(MethodOrderer.MethodName.class)
112 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
113 @TestPropertySource(properties = { //
114 "server.ssl.key-store=./config/keystore.jks", //
115 "app.webclient.trust-store=./config/truststore.jks", //
116 "app.webclient.trust-store-used=true", //
117 "app.vardata-directory=/tmp/pmstest", //
119 "app.s3.bucket=" // If this is set, S3 will be used to store data.
121 class ApplicationTest {
122 private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
125 ApplicationContext context;
131 private Policies policies;
134 private PolicyTypes policyTypes;
137 MockA1ClientFactory a1ClientFactory;
140 private ObjectMapper objectMapper;
143 RicSupervision supervision;
146 ApplicationConfig applicationConfig;
152 RappSimulatorController rAppSimulator;
155 RefreshConfigTask refreshConfigTask;
158 SecurityContext securityContext;
161 OpenPolicyAgentSimulatorController openPolicyAgentSimulatorController;
164 * Overrides the BeanFactory.
167 static class TestBeanFactory {
170 A1ClientFactory getA1ClientFactory(@Autowired ApplicationConfig appConfig, @Autowired PolicyTypes types) {
171 return new MockA1ClientFactory(appConfig, types);
175 public ServiceSupervision getServiceSupervision(@Autowired Services services,
176 @Autowired A1ClientFactory a1ClientFactory, @Autowired Policies policies) {
177 Duration checkInterval = Duration.ofMillis(1);
178 return new ServiceSupervision(services, policies, a1ClientFactory, checkInterval);
182 public ServletWebServerFactory servletContainer() {
183 return new TomcatServletWebServerFactory();
192 this.applicationConfig.setAuthProviderUrl(baseUrl() + OpenPolicyAgentSimulatorController.ACCESS_CONTROL_URL);
197 a1ClientFactory.reset();
206 a1ClientFactory.reset();
207 this.rAppSimulator.getTestResults().clear();
208 this.a1ClientFactory.setPolicyTypes(policyTypes); // Default same types in RIC and in this app
209 this.securityContext.setAuthTokenFilePath(null);
210 this.openPolicyAgentSimulatorController.getTestResults().reset();
214 static void clearTestDir() {
216 FileSystemUtils.deleteRecursively(Path.of("/tmp/pmstest"));
217 } catch (Exception e) {
218 logger.warn("Could test directory : {}", e.getMessage());
223 void verifyNoRicLocks() {
224 for (Ric ric : this.rics.getRics()) {
225 Lock.Grant grant = ric.getLock().lockBlocking(LockType.EXCLUSIVE, "verifyNoRicLocks");
226 grant.unlockBlocking();
227 assertThat(ric.getLock().getLockCounter()).isZero();
228 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
233 @DisplayName("test ZZ Actuator")
234 void testZZActuator() throws Exception {
235 // The test must be run last, hence the "ZZ" in the name. All succeeding tests
237 AsyncRestClient client = restClient(baseUrl(), false);
239 client.post("/actuator/loggers/org.onap.ccsdk.oran.a1policymanagementservice",
240 "{\"configuredLevel\":\"trace\"}").block();
242 String resp = client.get("/actuator/loggers/org.onap.ccsdk.oran.a1policymanagementservice").block();
243 assertThat(resp).contains("TRACE");
245 client.post("/actuator/loggers/org.springframework.boot.actuate", "{\"configuredLevel\":\"trace\"}").block();
247 // This will stop the web server and all coming tests will fail.
248 ResponseEntity<String> entity = client.postForEntity("/actuator/shutdown", "").block();
249 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
250 assertThat(((String) entity.getBody())).contains("Shutting down");
254 @DisplayName("test Persistency Policies")
255 void testPersistencyPolicies() throws Exception {
256 Ric ric = this.addRic("ric1");
257 PolicyType type = this.addPolicyType("type1", ric.id());
259 final int noOfPolicies = 100;
260 for (int i = 0; i < noOfPolicies; ++i) {
261 addPolicy("id" + i, type.getId(), "service", ric.id());
266 Policies policies = new Policies(this.applicationConfig);
267 policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
268 assertThat(policies.size()).isEqualTo(noOfPolicies);
272 restClient().delete("/policies/id2").block();
273 Policies policies = new Policies(this.applicationConfig);
274 policies.restoreFromDatabase(ric, this.policyTypes).blockLast();
275 assertThat(policies.size()).isEqualTo(noOfPolicies - 1);
280 @DisplayName("test Persistency Policy Types")
281 void testPersistencyPolicyTypes() throws Exception {
282 Ric ric = this.addRic("ric1");
283 this.addPolicyType("type1", ric.id());
286 PolicyTypes types = new PolicyTypes(this.applicationConfig);
287 types.restoreFromDatabase().blockLast();
288 assertThat(types.size()).isEqualTo(1);
291 @SuppressWarnings("squid:S2925") // "Thread.sleep" should not be used in tests.
292 private void waitforS3() throws Exception {
293 if (applicationConfig.isS3Enabled()) {
299 @DisplayName("test Persistency Service")
300 void testPersistencyService() throws Exception {
301 final String SERVICE = "serviceName";
302 putService(SERVICE, 1234, HttpStatus.CREATED);
303 assertThat(this.services.size()).isEqualTo(1);
304 Service service = this.services.getService(SERVICE);
307 Services servicesRestored = new Services(this.applicationConfig);
308 servicesRestored.restoreFromDatabase().blockLast();
309 Service serviceRestored = servicesRestored.getService(SERVICE);
310 assertThat(servicesRestored.size()).isEqualTo(1);
311 assertThat(serviceRestored.getCallbackUrl()).isEqualTo(service.getCallbackUrl());
312 assertThat(serviceRestored.getKeepAliveInterval()).isEqualTo(service.getKeepAliveInterval());
314 // check that the service can be deleted
315 this.services.remove(SERVICE);
316 servicesRestored = new Services(this.applicationConfig);
317 assertThat(servicesRestored.size()).isZero();
321 @DisplayName("test Adding Ric From Configuration")
322 void testAddingRicFromConfiguration() throws Exception {
323 // Test adding the RIC from configuration
325 final String RIC = "ric1";
326 final String TYPE = "type123";
327 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
328 nearRtRicPolicyTypes.put(createPolicyType(TYPE));
329 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
331 putService("service");
333 refreshConfigTask.handleUpdatedRicConfig( //
334 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
336 waitForRicState(RIC, RicState.AVAILABLE);
338 // Test that the type has been synched
339 Ric addedRic = this.rics.getRic(RIC);
340 assertThat(addedRic.getSupportedPolicyTypes()).hasSize(1);
341 assertThat(addedRic.getSupportedPolicyTypes().iterator().next().getId()).isEqualTo(TYPE);
343 // Check that a service callback for the AVAILABLE RIC is invoked
344 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
345 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
346 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
347 assertThat(callbackInfo.ricId).isEqualTo(RIC);
348 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
352 @DisplayName("test Adding Ric From Configuration non Responding Ric")
353 void testAddingRicFromConfiguration_nonRespondingRic() throws Exception {
354 putService("service");
356 final String RIC = "NonRespondingRic";
357 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(RIC);
358 doReturn(MockA1Client.monoError("error", HttpStatus.BAD_GATEWAY)).when(a1Client).getPolicyTypeIdentities();
360 refreshConfigTask.handleUpdatedRicConfig( //
361 new RicConfigUpdate(ricConfig(RIC, "me1"), RicConfigUpdate.Type.ADDED)) //
364 waitForRicState(RIC, RicState.UNAVAILABLE);
366 // Check that no service callback for the UNAVAILABLE RIC is invoked
367 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
368 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).isEmpty());
370 // Run a synch and check that the AVAILABLE notification is received
371 a1ClientFactory.reset();
372 supervision.checkAllRics();
373 waitForRicState(RIC, RicState.AVAILABLE);
375 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
379 @DisplayName("test Trust Validation")
380 void testTrustValidation() {
383 String rsp = restClient(true).get("/rics").block(); // restClient(true) enables trust validation
384 assertThat(rsp).contains("ric1");
389 @DisplayName("test Get Rics")
390 void testGetRics() throws Exception {
392 this.addPolicyType("type1", "ric1");
393 String url = "/rics?policytype_id=type1";
394 String rsp = restClient().get(url).block();
395 String expectedResponse = "{\"rics\":[{\"managed_element_ids\":[],\"ric_id\":\"ric1\", \"state\":\"AVAILABLE\",\"policytype_ids\":[\"type1\"]}]}";
396 assertEquals(objectMapper.readTree(expectedResponse), objectMapper.readTree(rsp));
398 // nameless type for ORAN A1 1.1
400 this.addPolicyType("", "ric2");
401 url = "/rics?policytype_id=";
402 rsp = restClient().get(url).block();
403 assertThat(rsp).contains("ric2") //
404 .doesNotContain("ric1") //
405 .contains("AVAILABLE");
408 rsp = restClient().get("/rics").block();
409 assertThat(rsp).contains("ric2") //
412 // Non existing policy type
413 url = "/rics?policytype_id=XXXX";
414 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
418 @DisplayName("test Synchronization")
419 void testSynchronization() throws Exception {
420 // Two polictypes will be put in the NearRT RICs
421 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes(this.applicationConfig);
422 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
423 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
424 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
426 // One type and one instance added to the Policy Management Service's storage
427 final String ric1Name = "ric1";
428 Ric ric1 = addRic(ric1Name);
429 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
430 Ric ric2 = addRic("ric2");
432 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
433 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
435 String policyId = "policyId";
436 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
437 supervision.checkAllRics(); // The created policy should be put in the RIC
439 // Wait until synch is completed
440 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
441 waitForRicState(ric1Name, RicState.AVAILABLE);
442 waitForRicState("ric2", RicState.AVAILABLE);
444 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
445 assertThat(ricPolicies.size()).isEqualTo(1);
446 Policy ricPolicy = ricPolicies.get(policyId);
447 assertThat(ricPolicy.getJson()).isEqualTo(policy.getJson());
449 // Both types should be in the Policy Management Service's storage after the
451 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
452 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
456 @DisplayName("test Get Ric")
457 void testGetRic() throws Exception {
458 String ricId = "ric1";
459 String managedElementId = "kista_1";
460 addRic(ricId, managedElementId);
462 String url = "/rics/ric?managed_element_id=" + managedElementId;
463 String rsp = restClient().get(url).block();
464 RicInfo ricInfo = objectMapper.readValue(rsp, RicInfo.class);
465 assertThat(ricInfo.getRicId()).isEqualTo(ricId);
467 url = "/rics/ric?ric_id=" + ricId;
468 rsp = restClient().get(url).block();
469 ricInfo = objectMapper.readValue(rsp, RicInfo.class);
470 assertThat(ricInfo.getRicId()).isEqualTo(ricId);
472 // test GET RIC for ManagedElement that does not exist
473 url = "/rics/ric?managed_element_id=" + "junk";
474 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
477 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
480 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
481 boolean isTransient, String statusNotificationUri) throws JsonProcessingException {
482 PolicyInfo policyInfo = new PolicyInfo();
483 policyInfo.setPolicyId(policyInstanceId);
484 policyInfo.setPolicytypeId(policyTypeName);
485 policyInfo.setRicId(ricId);
486 policyInfo.setServiceId(serviceName);
487 policyInfo.setPolicyData(jsonString());
488 policyInfo.setTransient(isTransient);
489 policyInfo.setStatusNotificationUri(statusNotificationUri);
490 return objectMapper.writeValueAsString(policyInfo);
493 private String putPolicyBody(String serviceName, String ricId, String policyTypeName, String policyInstanceId) throws JsonProcessingException {
494 return putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, false, "statusUri");
498 @DisplayName("test Put Policy")
499 void testPutPolicy() throws Exception {
500 String serviceName = "service.1";
501 String ricId = "ric.1";
502 String policyTypeName = "type1_1.2.3";
503 String policyInstanceId = "instance_1.2.3";
505 putService(serviceName);
506 addPolicyType(policyTypeName, ricId);
508 // PUT a transient policy
509 String url = "/policies";
510 String policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId, true, "statusNotif");
511 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
513 restClient().put(url, policyBody).block();
515 // Check the authorization request
516 OpenPolicyAgentSimulatorController.TestResults res =
517 this.openPolicyAgentSimulatorController.getTestResults();
518 assertThat(res.receivedRequests).hasSize(1);
519 PolicyAuthorizationRequest req = res.receivedRequests.get(0);
520 assertThat(req.getInput().getAccessType()).isEqualTo(AccessType.WRITE);
521 assertThat(req.getInput().getPolicyTypeId()).isEqualTo(policyTypeName);
524 Policy policy = policies.getPolicy(policyInstanceId);
525 assertThat(policy).isNotNull();
526 assertThat(policy.getId()).isEqualTo(policyInstanceId);
527 assertThat(policy.getOwnerServiceId()).isEqualTo(serviceName);
528 assertThat(policy.getRic().id()).isEqualTo(ricId);
529 assertThat(policy.isTransient()).isTrue();
531 // Put a non transient policy
532 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
533 restClient().put(url, policyBody).block();
534 policy = policies.getPolicy(policyInstanceId);
535 assertThat(policy.isTransient()).isFalse();
537 url = "/policy-instances";
538 String rsp = restClient().get(url).block();
539 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
541 url = "/policies/" + policyInstanceId;
542 rsp = restClient().get(url).block();
544 assertThat(rsp).contains(policyBody);
546 // Test of error codes
548 policyBody = putPolicyBody(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
549 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
551 policyBody = putPolicyBody(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
552 addPolicyType(policyTypeName + "XX", "otherRic");
553 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
555 policyBody = putPolicyBody(serviceName, ricId, policyTypeName, policyInstanceId);
556 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
557 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
558 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
562 void testFineGrainedAuth() throws Exception {
563 final String POLICY_ID = "policyId";
564 final String RIC_ID = "ric1";
565 final String TYPE_ID = "typeName";
566 addPolicy(POLICY_ID, TYPE_ID, null, RIC_ID);
567 assertThat(policies.size()).isEqualTo(1);
569 this.applicationConfig
570 .setAuthProviderUrl(baseUrl() + OpenPolicyAgentSimulatorController.ACCESS_CONTROL_URL_REJECT);
571 String url = "/policy-instances";
572 String rsp = restClient().get(url).block();
573 assertThat(rsp).as("Response contains no policy instance ID.").contains("[]");
575 url = "/policies/" + POLICY_ID;
576 testErrorCode(restClient().delete(url), HttpStatus.UNAUTHORIZED, "Not authorized");
579 String policyBody = putPolicyBody(null, RIC_ID, TYPE_ID, POLICY_ID, false, null);
580 testErrorCode(restClient().put(url, policyBody), HttpStatus.UNAUTHORIZED, "Not authorized");
582 rsp = restClient().get(url).block();
583 assertThat(rsp).as("Response contains no policy instance ID.").contains("[]");
587 void testFineGrainedAuth_OPA_UNAVALIABLE() throws Exception {
588 final String POLICY_ID = "policyId";
589 final String RIC_ID = "ric1";
590 final String TYPE_ID = "typeName";
591 addPolicy(POLICY_ID, TYPE_ID, null, RIC_ID);
592 assertThat(policies.size()).isEqualTo(1);
594 this.applicationConfig.setAuthProviderUrl("junk");
596 String url = "/policy-instances";
597 String rsp = restClient().get(url).block();
598 assertThat(rsp).as("Response contains no policy instance ID.").contains("[]");
600 url = "/policies/" + POLICY_ID;
601 testErrorCode(restClient().delete(url), HttpStatus.UNAUTHORIZED, "Not authorized");
604 String policyBody = putPolicyBody(null, RIC_ID, TYPE_ID, POLICY_ID, false, null);
605 testErrorCode(restClient().put(url, policyBody), HttpStatus.UNAUTHORIZED, "Not authorized");
607 rsp = restClient().get(url).block();
608 assertThat(rsp).as("Response contains no policy instance ID.").contains("[]");
611 @DisplayName("test Put Policy No Service No Status Uri")
612 void testPutPolicy_NoServiceNoStatusUri() throws Exception {
613 String ricId = "ric.1";
614 String policyTypeName = "type1_1.2.3";
615 String policyInstanceId = "instance_1.2.3";
617 addPolicyType(policyTypeName, ricId);
619 // PUT a transient policy
620 String url = "/policies";
621 String policyBody = putPolicyBody(null, ricId, policyTypeName, policyInstanceId, true, null);
622 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
624 restClient().put(url, policyBody).block();
626 Policy policy = policies.getPolicy(policyInstanceId);
627 assertThat(policy).isNotNull();
628 assertThat(policy.getOwnerServiceId()).isBlank();
629 assertThat(policy.getStatusNotificationUri()).isBlank();
634 * Test that HttpStatus and body from failing REST call to A1 is passed on to
637 * @throws ServiceException
639 @DisplayName("test Error From Ric")
640 void testErrorFromRic() throws ServiceException, JsonProcessingException {
641 putService("service1");
642 addPolicyType("type1", "ric1");
644 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
645 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
646 String responseBody = "Refused";
647 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
649 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
650 responseBodyBytes, StandardCharsets.UTF_8, null);
651 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
654 String putBody = putPolicyBody("service1", "ric1", "type1", "id1");
655 String url = "/policies";
656 testErrorCode(restClient().put(url, putBody), httpStatus, responseBody);
659 this.addPolicy("instance1", "type1", "service1", "ric1");
660 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
661 testErrorCode(restClient().delete("/policies/instance1"), httpStatus, responseBody);
666 @DisplayName("test Put Typeless Policy")
667 void testPutTypelessPolicy() throws Exception {
668 putService("service1");
669 addPolicyType("", "ric1");
670 String body = putPolicyBody("service1", "ric1", "", "id1");
671 restClient().put("/policies", body).block();
673 String rsp = restClient().get("/policy-instances").block();
674 PolicyInfoList info = objectMapper.readValue(rsp, PolicyInfoList.class);
675 assertThat(info.getPolicies()).hasSize(1);
676 PolicyInfo policyInfo = info.getPolicies().iterator().next();
677 assertThat(policyInfo.getPolicyId()).isEqualTo("id1");
678 assertThat(policyInfo.getPolicytypeId()).isEmpty();
682 @DisplayName("test Update Service")
683 void testUpdateService() throws Exception {
685 this.addPolicy("policyId", "type1", "", "ric1");
687 String url = "/policies?service_id=";
688 String resp = restClient().get(url).block();
689 String expectedResponse = "{\"policy_ids\":[\"policyId\"]}";
690 assertEquals(expectedResponse, resp);
692 this.addPolicy("policyId", "type1", "service", "ric1");
693 url = "/policies?service_id=";
694 resp = restClient().get(url).block();
695 expectedResponse = "{\"policy_ids\":[]}";
696 assertEquals(expectedResponse, resp);
698 url = "/policies?service_id=service";
699 resp = restClient().get(url).block();
700 assertThat(resp).contains("[\"policyId\"]");
704 @DisplayName("test Refuse To Update Policy")
705 void testRefuseToUpdatePolicy() throws Exception {
706 // Test that only the json can be changed for a already created policy
707 // In this case service is attempted to be changed
709 this.addRic("ricXXX");
710 this.addPolicy("instance1", "type1", "service1", "ric1");
711 this.addPolicy("instance2", "type1", "service1", "ricXXX");
713 // Try change ric1 -> ricXXX
714 String bodyWrongRic = putPolicyBody("service1", "ricXXX", "type1", "instance1");
715 testErrorCode(restClient().put("/policies", bodyWrongRic), HttpStatus.CONFLICT);
719 @DisplayName("test Get Policy")
720 void testGetPolicy() throws Exception {
721 String url = "/policies/id";
722 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
724 String response = restClient().get(url).block();
725 PolicyInfo policyInfo = objectMapper.readValue(response, PolicyInfo.class);
726 String expectedResponse = "{\"ric_id\":\"ric1\",\"service_id\":\"service1\",\"policy_id\":\"id\",\"policy_data\":{\"servingCellNrcgi\":\"1\"},\"status_notification_uri\":\"/policy-status?id=XXX\",\"policytype_id\":\"typeName\",\"transient\":false}";
727 assertEquals(objectMapper.readTree(expectedResponse), objectMapper.readTree(response));
730 policies.remove(policy);
731 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
736 @DisplayName("test Delete Policy")
737 void testDeletePolicy() throws Exception {
738 String policyId = "id.1";
739 addPolicy(policyId, "typeName", "service1", "ric1");
740 assertThat(policies.size()).isEqualTo(1);
742 String url = "/policies/" + policyId;
743 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
745 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
746 assertThat(policies.size()).isZero();
748 // Delete a non existing policy
749 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
754 @DisplayName("test Get Policy Type")
755 void testGetPolicyType() throws Exception {
756 String typeId = "AC.D";
757 addPolicyType(typeId, "ric1");
759 waitForRicState("ric1", RicState.AVAILABLE);
761 String url = "/policy-types/" + typeId;
763 String response = this.restClient().get(url).block();
765 assertEquals("{\"policy_schema\":{\"title\":\"AC.D\"}}", response);
767 // Get non existing schema
768 url = "/policy-types/JUNK";
769 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
772 String createPolicyTypesJson(String... types) throws JsonProcessingException {
773 List<String> list = new ArrayList<>();
774 Collections.addAll(list, types);
775 PolicyTypeIdList ids = new PolicyTypeIdList();
776 ids.setPolicytypeIds(list);
777 return objectMapper.writeValueAsString(ids);
781 @DisplayName("test Get Policy Types")
782 void testGetPolicyTypes() throws Exception {
783 String TYPE_ID_1 = "A_type1_1.9.0";
784 String TYPE_ID_2 = "A_type1_2.0.0";
785 String TYPE_ID_3 = "A_type1_1.5.0";
786 String TYPE_ID_4 = "type3_1.9.0";
787 addPolicyType(TYPE_ID_1, "ric1");
788 addPolicyType(TYPE_ID_2, "ric2");
789 addPolicyType(TYPE_ID_3, "ric2");
790 addPolicyType(TYPE_ID_4, "ric2");
792 addPolicyType("junk", "ric2");
793 addPolicyType("junk_a.b.c", "ric2");
795 String url = "/policy-types";
796 String rsp = restClient().get(url).block();
797 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
799 url = "/policy-types?ric_id=ric1";
800 rsp = restClient().get(url).block();
801 String expResp = createPolicyTypesJson(TYPE_ID_1);
802 assertThat(rsp).isEqualTo(expResp);
804 // Get policy types for non existing RIC
805 url = "/policy-types?ric_id=ric1XXX";
806 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
808 // All types with a type_name
809 url = "/policy-types?type_name=A_type1";
810 rsp = restClient().get(url).block();
811 assertThat(rsp).contains(TYPE_ID_1, TYPE_ID_2);
813 // All types compatible with type1_1.5.0 (which is type1_1.9.0)
814 url = "/policy-types?type_name=A_type1&&compatible_with_version=1.5.0";
815 rsp = restClient().get(url).block();
816 expResp = createPolicyTypesJson(TYPE_ID_3, TYPE_ID_1);
817 assertThat(rsp).isEqualTo(expResp);
819 url = "/policy-types?type_name=A_type1&&compatible_with_version=junk";
820 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Version must contain major.minor.patch code");
822 url = "/policy-types?type_name=A_type1&&compatible_with_version=a.b.c";
823 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "Syntax error in");
825 url = "/policy-types?compatible_with_version=1.5.0";
826 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST, "type_name");
830 @DisplayName("test Get Policy Instances")
831 void testGetPolicyInstances() throws Exception {
832 addPolicy("id1", "type1", "service1");
834 String url = "/policy-instances";
835 String response = restClient().get(url).block();
836 logger.info(response);
837 PolicyInfoList policyInfoList = objectMapper.readValue(response, PolicyInfoList.class);
838 assertThat(policyInfoList.getPolicies()).hasSize(1);
839 PolicyInfo policyInfo = policyInfoList.getPolicies().iterator().next();
840 assertThat(policyInfo.getPolicyId()).isEqualTo("id1");
841 assertThat(policyInfo.getPolicytypeId()).isEqualTo("type1");
842 assertThat(policyInfo.getServiceId()).isEqualTo("service1");
846 @DisplayName("test Get Policy Instances Filter")
847 void testGetPolicyInstancesFilter() throws Exception {
848 addPolicy("id1", "type1", "service1");
849 addPolicy("id2", "type1", "service2");
850 addPolicy("id3", "type2", "service1");
851 addPolicy("id4", "type1_1.0.0", "service1");
853 String url = "/policy-instances?policytype_id=type1";
854 String rsp = restClient().get(url).block();
856 assertThat(rsp).contains("id1")
858 .doesNotContain("id3");
860 url = "/policy-instances?policytype_id=type1&service_id=service2";
861 rsp = restClient().get(url).block();
863 assertThat(rsp).doesNotContain("id1")
865 .doesNotContain("id3");
867 url = "/policy-instances?type_name=type1";
868 rsp = restClient().get(url).block();
869 assertThat(rsp).contains("id1") //
871 .doesNotContain("id3")
874 // Test get policies for non existing type
875 url = "/policy-instances?policytype_id=type1XXX";
876 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
878 // Test get policies for non existing RIC
879 url = "/policy-instances?ric_id=XXX";
880 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
884 @DisplayName("test Get Policy Ids Filter")
885 void testGetPolicyIdsFilter() throws Exception {
886 addPolicy("id1", "type1", "service1", "ric1");
887 addPolicy("id2", "type1", "service2", "ric1");
888 addPolicy("id3", "type2", "service1", "ric1");
889 addPolicy("id4", "type1_1.0.0", "service1");
891 String url = "/policies?policytype_id=type1";
892 String rsp = restClient().get(url).block();
894 assertThat(rsp).contains("id1")
896 .doesNotContain("id3");
898 url = "/policies?policytype_id=type1&service_id=service1&ric=ric1";
899 rsp = restClient().get(url).block();
900 PolicyIdList respList = objectMapper.readValue(rsp, PolicyIdList.class);
901 assertThat(respList.getPolicyIds().iterator().next()).isEqualTo("id1");
903 url = "/policies?type_name=type1&service_id=service1";
904 rsp = restClient().get(url).block();
905 assertThat(rsp).contains("id1").contains("id4");
906 assertThat(objectMapper.readValue(rsp, PolicyIdList.class).getPolicyIds()).hasSize(2);
908 // Test get policy ids for non existing type
909 url = "/policies?policytype_id=type1XXX";
910 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
912 // Test get policy ids for non existing RIC
913 url = "/policies?ric_id=XXX";
914 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
919 @DisplayName("test Put And Get Service")
920 void testPutAndGetService() throws Exception {
922 String serviceName = "ac.dc";
923 putService(serviceName, 0, HttpStatus.CREATED);
924 putService(serviceName, 0, HttpStatus.OK);
927 String url = "/services?service_id=" + serviceName;
928 String rsp = restClient().get(url).block();
929 ServiceStatusList info = objectMapper.readValue(rsp, ServiceStatusList.class);
930 assertThat(info.getServiceList()).hasSize(1);
931 ServiceStatus status = info.getServiceList().iterator().next();
932 assertThat(status.getKeepAliveIntervalSeconds()).isZero();
933 assertThat(status.getServiceId()).isEqualTo(serviceName);
937 rsp = restClient().get(url).block();
938 assertThat(rsp).as("Response contains service name").contains(serviceName);
942 url = "/services/" + serviceName + "/keepalive";
943 ResponseEntity<?> entity = restClient().putForEntity(url).block();
944 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
947 addPolicy("id1", "type1", serviceName);
948 assertThat(services.size()).isEqualTo(1);
949 url = "/services/" + serviceName;
950 restClient().delete(url).block();
951 assertThat(services.size()).isZero();
953 // Keep alive, no registered service
954 testErrorCode(restClient().put("/services/junk/keepalive", ""), HttpStatus.NOT_FOUND);
956 // PUT service with bad payload
957 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
958 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
959 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
961 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
962 HttpStatus.BAD_REQUEST, false);
964 // GET non existing service
965 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
969 @DisplayName("test delete Service with no authorization")
970 void testDeleteServiceWithNoAuth() throws Exception {
972 String serviceName = "ac.dc";
973 putService(serviceName, 0, HttpStatus.CREATED);
975 // No Authorization to Delete
976 this.applicationConfig
977 .setAuthProviderUrl(baseUrl() + OpenPolicyAgentSimulatorController.ACCESS_CONTROL_URL_REJECT);
978 addPolicy("id1", "type1", serviceName);
979 assertThat(services.size()).isEqualTo(1);
980 String url = "/services/" + serviceName;
981 restClient().delete(url).block();
982 assertThat(services.size()).isZero();
983 assertThat(policies.size()).isEqualTo(1);
984 testErrorCode(restClient().get("/policies/id1"), HttpStatus.UNAUTHORIZED);
988 @DisplayName("test delete Service with no service")
989 void testDeleteServiceWithNoService() {
990 String url = "/services/" + "NoService";
991 testErrorCode(restClient().delete(url), HttpStatus.NOT_FOUND);
995 @DisplayName("test Service Supervision")
996 void testServiceSupervision() throws Exception {
997 putService("service1", 2, HttpStatus.CREATED);
998 addPolicyType("type1", "ric1");
1000 String policyBody = putPolicyBody("service1", "ric1", "type1", "instance1");
1001 restClient().put("/policies", policyBody).block();
1003 assertThat(policies.size()).isEqualTo(1);
1004 assertThat(services.size()).isEqualTo(1);
1006 // Timeout after ~2 second
1007 await().untilAsserted(() -> assertThat(policies.size()).isZero());
1008 assertThat(services.size()).isZero();
1012 @DisplayName("test Get Policy Status")
1013 void testGetPolicyStatus() throws Exception {
1014 addPolicy("id", "typeName", "service1", "ric1");
1015 assertThat(policies.size()).isEqualTo(1);
1017 String url = "/policies/id/status";
1018 String response = restClient().get(url).block();
1019 PolicyStatusInfo info = objectMapper.readValue(response, PolicyStatusInfo.class);
1020 assertThat(info.getStatus()).isEqualTo("OK");
1022 // GET non existing policy status
1023 url = "/policies/XXX/status";
1024 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
1026 // GET STATUS, the NearRT RIC returns error
1027 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
1028 url = "/policies/id/status";
1029 WebClientResponseException a1Exception = new WebClientResponseException(404, "", null, null, null);
1030 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
1031 response = restClient().get(url).block();
1032 info = objectMapper.readValue(response, PolicyStatusInfo.class);
1033 assertThat(info.getStatus()).hasToString("{}");
1037 @DisplayName("test Get Service Status")
1038 void testGetServiceStatus() {
1039 String url = "/status";
1040 String rsp = restClient().get(url).block();
1041 assertThat(rsp).contains("success");
1043 rsp = restClient(baseUrl(), false).get(url).block(); // V1 status is used by a readinessProbe
1044 assertThat(rsp).isEqualTo("success");
1048 @DisplayName("test Service Notification")
1049 void testServiceNotification() throws Exception {
1051 final String AUTH_TOKEN = "testToken";
1052 Path authFile = Files.createTempFile("pmsTestAuthToken", ".txt");
1053 Files.write(authFile, AUTH_TOKEN.getBytes());
1054 this.securityContext.setAuthTokenFilePath(authFile);
1056 putService("junkService");
1057 Service junkService = this.services.get("junkService");
1058 junkService.setCallbackUrl("https://junk");
1059 putService("service");
1061 Ric ric = addRic("ric1");
1062 ric.setState(Ric.RicState.UNAVAILABLE);
1063 supervision.checkAllRics();
1064 waitForRicState("ric1", RicState.AVAILABLE);
1066 final RappSimulatorController.TestResults receivedCallbacks = rAppSimulator.getTestResults();
1067 await().untilAsserted(() -> assertThat(receivedCallbacks.getReceivedInfo()).hasSize(1));
1068 ServiceCallbackInfo callbackInfo = receivedCallbacks.getReceivedInfo().get(0);
1069 assertThat(callbackInfo.ricId).isEqualTo("ric1");
1070 assertThat(callbackInfo.eventType).isEqualTo(ServiceCallbackInfo.EventType.AVAILABLE);
1072 var headers = receivedCallbacks.receivedHeaders.get(0);
1073 assertThat(headers).containsEntry("authorization", "Bearer " + AUTH_TOKEN);
1075 Files.delete(authFile);
1078 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
1081 Policy policy = Policy.builder()
1083 .json(objectMapper.writeValueAsString(jsonString()))
1084 .ownerServiceId(service)
1085 .ric(rics.getRic(ric))
1086 .type(addPolicyType(typeName, ric))
1087 .lastModified(Instant.now())
1089 .statusNotificationUri("/policy-status?id=XXX")
1091 policies.put(policy);
1093 } catch (JsonProcessingException ex) {
1094 throw new RuntimeException(ex);
1098 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
1099 return addPolicy(id, typeName, service, "ric");
1102 private String createServiceJson(String name, long keepAliveIntervalSeconds) throws JsonProcessingException {
1103 String callbackUrl = baseUrl() + RappSimulatorController.SERVICE_CALLBACK_URL;
1104 return createServiceJson(name, keepAliveIntervalSeconds, callbackUrl);
1107 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) throws JsonProcessingException {
1108 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name)
1109 .keepAliveIntervalSeconds(keepAliveIntervalSeconds)
1112 return objectMapper.writeValueAsString(service);
1115 private void putService(String name) throws JsonProcessingException {
1116 putService(name, 0, null);
1119 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) throws JsonProcessingException {
1120 String url = "/services";
1121 String body = createServiceJson(name, keepAliveIntervalSeconds);
1122 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
1123 if (expectedStatus != null) {
1124 assertNotNull(resp);
1125 assertEquals(expectedStatus, resp.getStatusCode(), "");
1129 private Map<String,String> jsonString() {
1130 Map<String,String> policyDataInMap = new HashMap<>();
1131 policyDataInMap.put("servingCellNrcgi","1");
1132 return policyDataInMap;
1136 @DisplayName("test Concurrency")
1137 void testConcurrency() throws Exception {
1138 this.applicationConfig.setAuthProviderUrl("");
1139 logger.info("Concurrency test starting");
1140 final Instant startTime = Instant.now();
1141 List<Thread> threads = new ArrayList<>();
1142 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
1143 a1ClientFactory.setResponseDelay(Duration.ofMillis(2));
1145 addPolicyType("type1", "ric");
1146 addPolicyType("type2", "ric");
1148 final String NON_RESPONDING_RIC = "NonRespondingRic";
1149 Ric nonRespondingRic = addRic(NON_RESPONDING_RIC);
1150 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client(NON_RESPONDING_RIC);
1151 a1Client.setErrorInject("errorInject");
1153 for (int i = 0; i < 10; ++i) {
1154 AsyncRestClient restClient = restClient();
1155 ConcurrencyTestRunnable test =
1156 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
1157 Thread thread = new Thread(test, "TestThread_" + i);
1159 threads.add(thread);
1162 for (Thread t : threads) {
1165 for (ConcurrencyTestRunnable test : tests) {
1166 assertThat(test.isFailed()).isFalse();
1168 assertThat(policies.size()).isZero();
1169 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
1171 assertThat(nonRespondingRic.getState()).isEqualTo(RicState.UNAVAILABLE);
1172 nonRespondingRic.setState(RicState.AVAILABLE);
1175 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
1176 WebClientConfig config = this.applicationConfig.getWebClientConfig();
1177 config = WebClientConfig.builder()
1178 .keyStoreType(config.getKeyStoreType())
1179 .keyStorePassword(config.getKeyStorePassword())
1180 .keyStore(config.getKeyStore())
1181 .keyPassword(config.getKeyPassword())
1182 .isTrustStoreUsed(useTrustValidation)
1183 .trustStore(config.getTrustStore())
1184 .trustStorePassword(config.getTrustStorePassword())
1185 .httpProxyConfig(config.getHttpProxyConfig())
1188 AsyncRestClientFactory f = new AsyncRestClientFactory(config, new SecurityContext(""));
1189 return f.createRestClientNoHttpProxy(baseUrl);
1193 private String baseUrl() {
1194 return "https://localhost:" + port;
1197 private AsyncRestClient restClient(boolean useTrustValidation) {
1198 return restClient(baseUrl() + Consts.V2_API_ROOT, useTrustValidation);
1201 private AsyncRestClient restClient() {
1202 return restClient(false);
1205 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
1206 testErrorCode(request, expStatus, "", true);
1209 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
1210 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
1213 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
1214 testErrorCode(request, expStatus, responseContains, true);
1217 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
1218 boolean expectApplicationProblemJsonMediaType) {
1219 StepVerifier.create(request)
1220 .expectSubscription()
1221 .expectErrorMatches(
1222 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType))
1226 private void waitForRicState(String ricId, RicState state) throws ServiceException {
1227 Ric ric = rics.getRic(ricId);
1228 await().untilAsserted(() -> state.equals(ric.getState()));
1231 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
1232 boolean expectApplicationProblemJsonMediaType) {
1233 assertTrue(throwable instanceof WebClientResponseException);
1234 WebClientResponseException responseException = (WebClientResponseException) throwable;
1235 String body = responseException.getResponseBodyAsString();
1236 assertThat(body).contains(responseContains);
1237 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
1239 if (expectApplicationProblemJsonMediaType) {
1240 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
1245 private MockA1Client getA1Client(String ricId) {
1246 return a1ClientFactory.getOrCreateA1Client(ricId);
1249 private PolicyType createPolicyType(String policyTypeName) {
1250 return PolicyType.builder()
1252 .schema("{\"title\":\"" + policyTypeName + "\"}")
1256 private PolicyType addPolicyType(String policyTypeName, String ricId) {
1257 PolicyType type = createPolicyType(policyTypeName);
1258 policyTypes.put(type);
1259 addRic(ricId).addSupportedPolicyType(type);
1263 private Ric addRic(String ricId) {
1264 return addRic(ricId, null);
1267 private RicConfig ricConfig(String ricId, String managedElement) {
1268 List<String> mes = new ArrayList<>();
1269 if (managedElement != null) {
1270 mes.add(managedElement);
1272 return RicConfig.builder()
1275 .managedElementIds(mes)
1279 private Ric addRic(String ricId, String managedElement) {
1280 if (rics.get(ricId) != null) {
1281 return rics.get(ricId);
1284 RicConfig conf = ricConfig(ricId, managedElement);
1285 Ric ric = new Ric(conf);
1286 ric.setState(Ric.RicState.AVAILABLE);