2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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.oransc.policyagent;
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;
32 import com.google.gson.JsonArray;
33 import com.google.gson.JsonElement;
34 import com.google.gson.JsonParser;
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.List;
42 import org.junit.jupiter.api.AfterEach;
43 import org.junit.jupiter.api.BeforeEach;
44 import org.junit.jupiter.api.Test;
45 import org.junit.jupiter.api.extension.ExtendWith;
46 import org.oransc.policyagent.clients.AsyncRestClient;
47 import org.oransc.policyagent.configuration.ApplicationConfig;
48 import org.oransc.policyagent.configuration.ImmutableRicConfig;
49 import org.oransc.policyagent.configuration.ImmutableWebClientConfig;
50 import org.oransc.policyagent.configuration.RicConfig;
51 import org.oransc.policyagent.configuration.WebClientConfig;
52 import org.oransc.policyagent.controllers.PolicyInfo;
53 import org.oransc.policyagent.controllers.ServiceRegistrationInfo;
54 import org.oransc.policyagent.controllers.ServiceStatus;
55 import org.oransc.policyagent.exceptions.ServiceException;
56 import org.oransc.policyagent.repository.ImmutablePolicy;
57 import org.oransc.policyagent.repository.ImmutablePolicyType;
58 import org.oransc.policyagent.repository.Lock.LockType;
59 import org.oransc.policyagent.repository.Policies;
60 import org.oransc.policyagent.repository.Policy;
61 import org.oransc.policyagent.repository.PolicyType;
62 import org.oransc.policyagent.repository.PolicyTypes;
63 import org.oransc.policyagent.repository.Ric;
64 import org.oransc.policyagent.repository.Ric.RicState;
65 import org.oransc.policyagent.repository.Rics;
66 import org.oransc.policyagent.repository.Services;
67 import org.oransc.policyagent.tasks.RicSupervision;
68 import org.oransc.policyagent.tasks.ServiceSupervision;
69 import org.oransc.policyagent.utils.MockA1Client;
70 import org.oransc.policyagent.utils.MockA1ClientFactory;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
73 import org.springframework.beans.factory.annotation.Autowired;
74 import org.springframework.boot.test.context.SpringBootTest;
75 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
76 import org.springframework.boot.test.context.TestConfiguration;
77 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
78 import org.springframework.boot.web.server.LocalServerPort;
79 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
80 import org.springframework.context.ApplicationContext;
81 import org.springframework.context.annotation.Bean;
82 import org.springframework.http.HttpStatus;
83 import org.springframework.http.ResponseEntity;
84 import org.springframework.test.context.TestPropertySource;
85 import org.springframework.test.context.junit.jupiter.SpringExtension;
86 import org.springframework.web.reactive.function.client.WebClientResponseException;
88 import reactor.core.publisher.Mono;
89 import reactor.test.StepVerifier;
90 import reactor.util.annotation.Nullable;
92 @ExtendWith(SpringExtension.class)
93 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
96 "server.ssl.key-store=./config/keystore.jks", //
97 "app.webclient.trust-store=./config/truststore.jks"})
98 class ApplicationTest {
99 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
102 ApplicationContext context;
108 private Policies policies;
111 private PolicyTypes policyTypes;
114 MockA1ClientFactory a1ClientFactory;
117 RicSupervision supervision;
120 ApplicationConfig applicationConfig;
125 private static Gson gson = new GsonBuilder() //
129 public static class MockApplicationConfig extends ApplicationConfig {
131 public String getLocalConfigurationFilePath() {
132 return ""; // No config file loaded for the test
137 * Overrides the BeanFactory.
140 static class TestBeanFactory {
141 private final PolicyTypes policyTypes = new PolicyTypes();
142 private final Services services = new Services();
143 private final Policies policies = new Policies();
144 MockA1ClientFactory a1ClientFactory = null;
147 public ApplicationConfig getApplicationConfig() {
148 return new MockApplicationConfig();
152 MockA1ClientFactory getA1ClientFactory() {
153 if (a1ClientFactory == null) {
154 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
156 return this.a1ClientFactory;
160 public PolicyTypes getPolicyTypes() {
161 return this.policyTypes;
165 Policies getPolicies() {
166 return this.policies;
170 Services getServices() {
171 return this.services;
175 public ServiceSupervision getServiceSupervision() {
176 Duration checkInterval = Duration.ofMillis(1);
177 return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
181 public ServletWebServerFactory servletContainer() {
182 return new TomcatServletWebServerFactory();
196 a1ClientFactory.reset();
200 void verifyNoRicLocks() {
201 for (Ric ric : this.rics.getRics()) {
202 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
203 ric.getLock().unlockBlocking();
204 assertThat(ric.getLock().getLockCounter()).isZero();
205 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
210 void testGetRics() throws Exception {
212 this.addPolicyType("type1", "ric1");
213 String url = "/rics?policyType=type1";
214 String rsp = restClient().get(url).block();
215 assertThat(rsp).contains("ric1");
217 // nameless type for ORAN A1 1.1
219 this.addPolicyType("", "ric2");
220 url = "/rics?policyType=";
222 // This tests also validation of trusted certs restClient(true)
223 rsp = restClient(true).get(url).block();
224 assertThat(rsp).contains("ric2") //
225 .doesNotContain("ric1") //
226 .contains("AVAILABLE");
229 rsp = restClient().get("/rics").block();
230 assertThat(rsp).contains("ric2") //
233 // Non existing policy type
234 url = "/rics?policyType=XXXX";
235 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
239 void testSynchronization() throws Exception {
240 // Two polictypes will be put in the NearRT RICs
241 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
242 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
243 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
244 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
246 // One type and one instance added to the agent storage
247 final String ric1Name = "ric1";
248 Ric ric1 = addRic(ric1Name);
249 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
250 Ric ric2 = addRic("ric2");
252 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC
253 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
255 String policyId = "policyId";
256 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
257 supervision.checkAllRics(); // The created policy should be put in the RIC
259 // Wait until synch is completed
260 await().untilAsserted(() -> RicState.SYNCHRONIZING.equals(rics.getRic(ric1Name).getState()));
261 await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic(ric1Name).getState()));
262 await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic("ric2").getState()));
264 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
265 assertThat(ricPolicies.size()).isEqualTo(1);
266 Policy ricPolicy = ricPolicies.get(policyId);
267 assertThat(ricPolicy.json()).isEqualTo(policy.json());
269 // Both types should be in the agent storage after the synch
270 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
271 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
275 void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
276 String ricName = "ric1";
277 String managedElementId = "kista_1";
278 addRic(ricName, managedElementId);
280 String url = "/ric?managedElementId=" + managedElementId;
281 String rsp = restClient().get(url).block();
282 assertThat(rsp).isEqualTo(ricName);
284 // test GET RIC for ManagedElement that does not exist
285 url = "/ric?managedElementId=" + "junk";
286 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
289 private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId,
290 boolean isTransient) {
292 if (policyTypeName.isEmpty()) {
293 url = "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName;
295 url = "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName + "&type="
299 url += "&transient=true";
304 private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId) {
305 return putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId, false);
309 void testPutPolicy() throws Exception {
310 String serviceName = "service1";
311 String ricName = "ric1";
312 String policyTypeName = "type1";
313 String policyInstanceId = "instance1";
315 putService(serviceName);
316 addPolicyType(policyTypeName, ricName);
318 // PUT a transient policy
319 String url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId, true);
320 final String policyBody = jsonString();
321 this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
323 restClient().put(url, policyBody).block();
325 Policy policy = policies.getPolicy(policyInstanceId);
326 assertThat(policy).isNotNull();
327 assertThat(policy.id()).isEqualTo(policyInstanceId);
328 assertThat(policy.ownerServiceName()).isEqualTo(serviceName);
329 assertThat(policy.ric().name()).isEqualTo("ric1");
330 assertThat(policy.isTransient()).isTrue();
332 // Put a non transient policy
333 url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
334 restClient().put(url, policyBody).block();
335 policy = policies.getPolicy(policyInstanceId);
336 assertThat(policy.isTransient()).isFalse();
339 String rsp = restClient().get(url).block();
340 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
342 url = "/policy?id=" + policyInstanceId;
343 rsp = restClient().get(url).block();
344 assertThat(rsp).isEqualTo(policyBody);
346 // Test of error codes
347 url = putPolicyUrl(serviceName, ricName + "XX", policyTypeName, policyInstanceId);
348 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
350 url = putPolicyUrl(serviceName, ricName, policyTypeName + "XX", policyInstanceId);
351 addPolicyType(policyTypeName + "XX", "otherRic");
352 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
354 url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
355 this.rics.getRic(ricName).setState(Ric.RicState.SYNCHRONIZING);
356 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
357 this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
362 * Test that HttpStatus and body from failing REST call to A1 is passed on to the caller.
364 * @throws ServiceException
366 void testErrorFromRic() throws ServiceException {
367 putService("service1");
368 addPolicyType("type1", "ric1");
370 String url = putPolicyUrl("service1", "ric1", "type1", "id1");
371 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
372 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
373 String responseBody = "Refused";
374 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
376 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
377 responseBodyBytes, StandardCharsets.UTF_8, null);
378 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
381 testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
384 this.addPolicy("instance1", "type1", "service1", "ric1");
385 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
386 testErrorCode(restClient().delete("/policy?id=instance1"), httpStatus, responseBody);
389 this.addPolicy("instance1", "type1", "service1", "ric1");
390 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
391 testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus, responseBody);
393 // Check that empty response body is OK
394 a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
395 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
396 testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus);
400 void testPutTypelessPolicy() throws Exception {
401 putService("service1");
402 addPolicyType("", "ric1");
403 String url = putPolicyUrl("service1", "ric1", "", "id1");
404 restClient().put(url, jsonString()).block();
406 String rsp = restClient().get("/policies").block();
407 List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
408 assertThat(info).hasSize(1);
409 PolicyInfo policyInfo = info.get(0);
410 assertThat(policyInfo.id).isEqualTo("id1");
411 assertThat(policyInfo.type).isEmpty();
415 void testRefuseToUpdatePolicy() throws Exception {
416 // Test that only the json can be changed for a already created policy
417 // In this case service is attempted to be changed
419 this.addRic("ricXXX");
420 this.addPolicy("instance1", "type1", "service1", "ric1");
421 this.addPolicy("instance2", "type1", "service1", "ricXXX");
423 // Try change ric1 -> ricXXX
424 String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
425 testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
429 void testGetPolicy() throws Exception {
430 String url = "/policy?id=id";
431 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
433 String rsp = restClient().get(url).block();
434 assertThat(rsp).isEqualTo(policy.json());
437 policies.remove(policy);
438 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
443 void testDeletePolicy() throws Exception {
444 addPolicy("id", "typeName", "service1", "ric1");
445 assertThat(policies.size()).isEqualTo(1);
447 String url = "/policy?id=id";
448 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
450 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
451 assertThat(policies.size()).isZero();
453 // Delete a non existing policy
454 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
458 void testGetPolicySchemas() throws Exception {
459 addPolicyType("type1", "ric1");
460 addPolicyType("type2", "ric2");
462 String url = "/policy_schemas";
463 String rsp = this.restClient().get(url).block();
464 assertThat(rsp).contains("type1") //
465 .contains("[{\"title\":\"type2\"}");
467 List<String> info = parseSchemas(rsp);
468 assertThat(info).hasSize(2);
470 url = "/policy_schemas?ric=ric1";
471 rsp = restClient().get(url).block();
472 assertThat(rsp).contains("type1");
473 info = parseSchemas(rsp);
474 assertThat(info).hasSize(1);
476 // Get schema for non existing RIC
477 url = "/policy_schemas?ric=ric1XXX";
478 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
482 void testGetPolicySchema() throws Exception {
483 addPolicyType("type1", "ric1");
484 addPolicyType("type2", "ric2");
486 String url = "/policy_schema?id=type1";
487 String rsp = restClient().get(url).block();
489 assertThat(rsp).contains("type1") //
492 // Get non existing schema
493 url = "/policy_schema?id=type1XX";
494 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
498 void testGetPolicyTypes() throws Exception {
499 addPolicyType("type1", "ric1");
500 addPolicyType("type2", "ric2");
502 String url = "/policy_types";
503 String rsp = restClient().get(url).block();
504 assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
506 url = "/policy_types?ric=ric1";
507 rsp = restClient().get(url).block();
508 assertThat(rsp).isEqualTo("[\"type1\"]");
510 // Get policy types for non existing RIC
511 url = "/policy_types?ric=ric1XXX";
512 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
516 void testGetPolicies() throws Exception {
517 addPolicy("id1", "type1", "service1");
519 String url = "/policies";
520 String rsp = restClient().get(url).block();
522 List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
523 assertThat(info).hasSize(1);
524 PolicyInfo policyInfo = info.get(0);
525 assert (policyInfo.validate());
526 assertThat(policyInfo.id).isEqualTo("id1");
527 assertThat(policyInfo.type).isEqualTo("type1");
528 assertThat(policyInfo.service).isEqualTo("service1");
532 void testGetPoliciesFilter() throws Exception {
533 addPolicy("id1", "type1", "service1");
534 addPolicy("id2", "type1", "service2");
535 addPolicy("id3", "type2", "service1");
537 String url = "/policies?type=type1";
538 String rsp = restClient().get(url).block();
540 assertThat(rsp).contains("id1") //
542 .doesNotContain("id3");
544 url = "/policies?type=type1&service=service2";
545 rsp = restClient().get(url).block();
547 assertThat(rsp).doesNotContain("id1") //
549 .doesNotContain("id3");
551 // Test get policies for non existing type
552 url = "/policies?type=type1XXX";
553 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
555 // Test get policies for non existing RIC
556 url = "/policies?ric=XXX";
557 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
561 void testGetPolicyIdsFilter() throws Exception {
562 addPolicy("id1", "type1", "service1", "ric1");
563 addPolicy("id2", "type1", "service2", "ric1");
564 addPolicy("id3", "type2", "service1", "ric1");
566 String url = "/policy_ids?type=type1";
567 String rsp = restClient().get(url).block();
569 assertThat(rsp).contains("id1") //
571 .doesNotContain("id3");
573 url = "/policy_ids?type=type1&service=service1&ric=ric1";
574 rsp = restClient().get(url).block();
575 assertThat(rsp).isEqualTo("[\"id1\"]");
577 // Test get policy ids for non existing type
578 url = "/policy_ids?type=type1XXX";
579 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
581 // Test get policy ids for non existing RIC
582 url = "/policy_ids?ric=XXX";
583 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
587 void testPutAndGetService() throws Exception {
589 String serviceName = "name";
590 putService(serviceName, 0, HttpStatus.CREATED);
591 putService(serviceName, 0, HttpStatus.OK);
594 String url = "/services?name=name";
595 String rsp = restClient().get(url).block();
596 List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
597 assertThat(info).hasSize(1);
598 ServiceStatus status = info.iterator().next();
599 assertThat(status.keepAliveIntervalSeconds).isZero();
600 assertThat(status.serviceName).isEqualTo(serviceName);
604 rsp = restClient().get(url).block();
605 assertThat(rsp).as("Response contains service name").contains(serviceName);
609 url = "/services/keepalive?name=name";
610 ResponseEntity<String> entity = restClient().putForEntity(url).block();
611 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
614 assertThat(services.size()).isEqualTo(1);
615 url = "/services?name=name";
616 restClient().delete(url).block();
617 assertThat(services.size()).isZero();
619 // Keep alive, no registered service
620 testErrorCode(restClient().put("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
622 // PUT servive with bad payload
623 testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
624 testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
625 testErrorCode(restClient().put("/service", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST);
626 testErrorCode(restClient().put("/service", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
627 HttpStatus.BAD_REQUEST);
629 // GET non existing service
630 testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
634 void testServiceSupervision() throws Exception {
635 putService("service1", 1, HttpStatus.CREATED);
636 addPolicyType("type1", "ric1");
638 String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
639 final String policyBody = jsonString();
640 restClient().put(url, policyBody).block();
642 assertThat(policies.size()).isEqualTo(1);
643 assertThat(services.size()).isEqualTo(1);
645 // Timeout after ~1 second
646 await().untilAsserted(() -> assertThat(policies.size()).isZero());
647 assertThat(services.size()).isZero();
651 void testGetPolicyStatus() throws Exception {
652 addPolicy("id", "typeName", "service1", "ric1");
653 assertThat(policies.size()).isEqualTo(1);
655 String url = "/policy_status?id=id";
656 String rsp = restClient().get(url).block();
657 assertThat(rsp).isEqualTo("OK");
659 // GET non existing policy status
660 url = "/policy_status?id=XXX";
661 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
664 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
666 Policy policy = ImmutablePolicy.builder() //
668 .json(jsonString()) //
669 .ownerServiceName(service) //
670 .ric(rics.getRic(ric)) //
671 .type(addPolicyType(typeName, ric)) //
672 .lastModified("lastModified") //
673 .isTransient(false) //
675 policies.put(policy);
679 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
680 return addPolicy(id, typeName, service, "ric");
683 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
684 return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
687 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
688 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
690 String json = gson.toJson(service);
694 private void putService(String name) {
695 putService(name, 0, null);
698 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
699 String url = "/service";
700 String body = createServiceJson(name, keepAliveIntervalSeconds);
701 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
702 if (expectedStatus != null) {
703 assertEquals(expectedStatus, resp.getStatusCode(), "");
707 private String baseUrl() {
708 return "https://localhost:" + port;
711 private String jsonString() {
712 return "{\"servingCellNrcgi\":\"1\"}";
716 void testConcurrency() throws Exception {
717 final Instant startTime = Instant.now();
718 List<Thread> threads = new ArrayList<>();
719 a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
721 addPolicyType("type1", "ric");
722 addPolicyType("type2", "ric");
724 for (int i = 0; i < 10; ++i) {
726 new Thread(new ConcurrencyTestRunnable(baseUrl(), supervision, a1ClientFactory, rics, policyTypes),
731 for (Thread t : threads) {
734 assertThat(policies.size()).isZero();
735 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
738 private AsyncRestClient restClient(boolean useTrustValidation) {
739 WebClientConfig config = this.applicationConfig.getWebClientConfig();
740 config = ImmutableWebClientConfig.builder() //
741 .isTrustStoreUsed(useTrustValidation) //
742 .trustStore(config.trustStore()) //
743 .trustStorePassword(config.trustStorePassword()) //
746 return new AsyncRestClient(baseUrl(), config);
749 private AsyncRestClient restClient() {
750 return restClient(false);
753 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
754 testErrorCode(request, expStatus, "");
757 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
758 StepVerifier.create(request) //
759 .expectSubscription() //
760 .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
764 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains) {
765 assertTrue(throwable instanceof WebClientResponseException);
766 WebClientResponseException responseException = (WebClientResponseException) throwable;
767 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
768 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
772 private MockA1Client getA1Client(String ricName) throws ServiceException {
773 return a1ClientFactory.getOrCreateA1Client(ricName);
776 private PolicyType createPolicyType(String policyTypeName) {
777 return ImmutablePolicyType.builder() //
778 .name(policyTypeName) //
779 .schema("{\"title\":\"" + policyTypeName + "\"}") //
783 private PolicyType addPolicyType(String policyTypeName, String ricName) {
784 PolicyType type = createPolicyType(policyTypeName);
785 policyTypes.put(type);
786 addRic(ricName).addSupportedPolicyType(type);
790 private Ric addRic(String ricName) {
791 return addRic(ricName, null);
794 private Ric addRic(String ricName, String managedElement) {
795 if (rics.get(ricName) != null) {
796 return rics.get(ricName);
798 List<String> mes = new ArrayList<>();
799 if (managedElement != null) {
800 mes.add(managedElement);
802 RicConfig conf = ImmutableRicConfig.builder() //
805 .managedElementIds(mes) //
806 .controllerName("") //
808 Ric ric = new Ric(conf);
809 ric.setState(Ric.RicState.AVAILABLE);
814 private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
815 List<T> result = new ArrayList<>();
816 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
817 for (JsonElement jsonElement : jsonArr) {
818 T json = gson.fromJson(jsonElement.toString(), clazz);
824 private static List<String> parseSchemas(String jsonString) {
825 JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
826 List<String> result = new ArrayList<>();
827 for (JsonElement schemaObject : arrayOfSchema) {
828 result.add(schemaObject.toString());