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.nio.charset.StandardCharsets;
34 import java.time.Duration;
35 import java.time.Instant;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.List;
40 import org.junit.jupiter.api.AfterEach;
41 import org.junit.jupiter.api.BeforeEach;
42 import org.junit.jupiter.api.Test;
43 import org.junit.jupiter.api.extension.ExtendWith;
44 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
45 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
46 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableRicConfig;
47 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableWebClientConfig;
48 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
49 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
50 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
51 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
52 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
62 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
63 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
64 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
65 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68 import org.springframework.beans.factory.annotation.Autowired;
69 import org.springframework.boot.test.context.SpringBootTest;
70 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
71 import org.springframework.boot.test.context.TestConfiguration;
72 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
73 import org.springframework.boot.web.server.LocalServerPort;
74 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
75 import org.springframework.context.ApplicationContext;
76 import org.springframework.context.annotation.Bean;
77 import org.springframework.http.HttpStatus;
78 import org.springframework.http.MediaType;
79 import org.springframework.http.ResponseEntity;
80 import org.springframework.test.context.TestPropertySource;
81 import org.springframework.test.context.junit.jupiter.SpringExtension;
82 import org.springframework.web.reactive.function.client.WebClientResponseException;
84 import reactor.core.publisher.Mono;
85 import reactor.test.StepVerifier;
86 import reactor.util.annotation.Nullable;
88 @ExtendWith(SpringExtension.class)
89 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
92 "server.ssl.key-store=./config/keystore.jks", //
93 "app.webclient.trust-store=./config/truststore.jks"})
94 class ApplicationTest {
95 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
98 ApplicationContext context;
104 private Policies policies;
107 private PolicyTypes policyTypes;
110 MockA1ClientFactory a1ClientFactory;
113 RicSupervision supervision;
116 ApplicationConfig applicationConfig;
121 private static Gson gson = new GsonBuilder() //
125 public static class MockApplicationConfig extends ApplicationConfig {
127 public String getLocalConfigurationFilePath() {
128 return ""; // No config file loaded for the test
133 * Overrides the BeanFactory.
136 static class TestBeanFactory {
137 private final PolicyTypes policyTypes = new PolicyTypes();
138 private final Services services = new Services();
139 private final Policies policies = new Policies();
140 MockA1ClientFactory a1ClientFactory = null;
143 public ApplicationConfig getApplicationConfig() {
144 return new MockApplicationConfig();
148 MockA1ClientFactory getA1ClientFactory() {
149 if (a1ClientFactory == null) {
150 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
152 return this.a1ClientFactory;
156 public PolicyTypes getPolicyTypes() {
157 return this.policyTypes;
161 Policies getPolicies() {
162 return this.policies;
166 Services getServices() {
167 return this.services;
171 public ServiceSupervision getServiceSupervision() {
172 Duration checkInterval = Duration.ofMillis(1);
173 return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
177 public ServletWebServerFactory servletContainer() {
178 return new TomcatServletWebServerFactory();
192 a1ClientFactory.reset();
196 void verifyNoRicLocks() {
197 for (Ric ric : this.rics.getRics()) {
198 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
199 ric.getLock().unlockBlocking();
200 assertThat(ric.getLock().getLockCounter()).isZero();
201 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
206 void testGetRics() throws Exception {
208 this.addPolicyType("type1", "ric1");
209 String url = "/rics?policytype_id=type1";
210 String rsp = restClient().get(url).block();
211 assertThat(rsp).contains("ric1");
213 // nameless type for ORAN A1 1.1
215 this.addPolicyType("", "ric2");
216 url = "/rics?policytype_id=";
218 // This tests also validation of trusted certs restClient(true)
219 rsp = restClient(true).get(url).block();
220 assertThat(rsp).contains("ric2") //
221 .doesNotContain("ric1") //
222 .contains("AVAILABLE");
225 rsp = restClient().get("/rics").block();
226 assertThat(rsp).contains("ric2") //
229 // Non existing policy type
230 url = "/rics?policytype_id=XXXX";
231 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
235 void testSynchronization() throws Exception {
236 // Two polictypes will be put in the NearRT RICs
237 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
238 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
239 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
240 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
242 // One type and one instance added to the Policy Management Service's storage
243 final String ric1Name = "ric1";
244 Ric ric1 = addRic(ric1Name);
245 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
246 Ric ric2 = addRic("ric2");
248 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
249 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
251 String policyId = "policyId";
252 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
253 supervision.checkAllRics(); // The created policy should be put in the RIC
255 // Wait until synch is completed
256 await().untilAsserted(() -> RicState.SYNCHRONIZING.equals(rics.getRic(ric1Name).getState()));
257 await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic(ric1Name).getState()));
258 await().untilAsserted(() -> RicState.AVAILABLE.equals(rics.getRic("ric2").getState()));
260 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
261 assertThat(ricPolicies.size()).isEqualTo(1);
262 Policy ricPolicy = ricPolicies.get(policyId);
263 assertThat(ricPolicy.json()).isEqualTo(policy.json());
265 // Both types should be in the Policy Management Service's storage after the
267 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
268 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
272 void testGetRic() throws Exception {
273 String ricId = "ric1";
274 String managedElementId = "kista_1";
275 addRic(ricId, managedElementId);
277 String url = "/ric?managed_element_id=" + managedElementId;
278 String rsp = restClient().get(url).block();
279 RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
280 assertThat(ricInfo.ricId).isEqualTo(ricId);
282 url = "/ric?ric_id=" + ricId;
283 rsp = restClient().get(url).block();
284 ricInfo = gson.fromJson(rsp, RicInfo.class);
285 assertThat(ricInfo.ricId).isEqualTo(ricId);
287 // test GET RIC for ManagedElement that does not exist
288 url = "/ric?managed_element_id=" + "junk";
289 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
292 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
295 private String putPolicyUrl(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
296 boolean isTransient) {
298 if (policyTypeName.isEmpty()) {
299 url = "/policy?policy_id=" + policyInstanceId + "&ric_id=" + ricId + "&service_id=" + serviceName;
301 url = "/policy?policy_id=" + policyInstanceId + "&ric_id=" + ricId + "&service_id=" + serviceName
302 + "&policytype_id=" + policyTypeName;
305 url += "&transient=true";
310 private String putPolicyUrl(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
311 return putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId, false);
315 void testPutPolicy() throws Exception {
316 String serviceName = "service1";
317 String ricId = "ric1";
318 String policyTypeName = "type1";
319 String policyInstanceId = "instance1";
321 putService(serviceName);
322 addPolicyType(policyTypeName, ricId);
324 // PUT a transient policy
325 String url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId, true);
326 final String policyBody = jsonString();
327 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
329 restClient().put(url, policyBody).block();
331 Policy policy = policies.getPolicy(policyInstanceId);
332 assertThat(policy).isNotNull();
333 assertThat(policy.id()).isEqualTo(policyInstanceId);
334 assertThat(policy.ownerServiceId()).isEqualTo(serviceName);
335 assertThat(policy.ric().id()).isEqualTo("ric1");
336 assertThat(policy.isTransient()).isTrue();
338 // Put a non transient policy
339 url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId);
340 restClient().put(url, policyBody).block();
341 policy = policies.getPolicy(policyInstanceId);
342 assertThat(policy.isTransient()).isFalse();
345 String rsp = restClient().get(url).block();
346 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
348 url = "/policy?policy_id=" + policyInstanceId;
349 rsp = restClient().get(url).block();
350 assertThat(rsp).isEqualTo(policyBody);
352 // Test of error codes
353 url = putPolicyUrl(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
354 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
356 url = putPolicyUrl(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
357 addPolicyType(policyTypeName + "XX", "otherRic");
358 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
360 url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId);
361 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
362 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
363 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
368 * Test that HttpStatus and body from failing REST call to A1 is passed on to
371 * @throws ServiceException
373 void testErrorFromRic() throws ServiceException {
374 putService("service1");
375 addPolicyType("type1", "ric1");
377 String url = putPolicyUrl("service1", "ric1", "type1", "id1");
378 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
379 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
380 String responseBody = "Refused";
381 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
383 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
384 responseBodyBytes, StandardCharsets.UTF_8, null);
385 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
388 testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
391 this.addPolicy("instance1", "type1", "service1", "ric1");
392 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
393 testErrorCode(restClient().delete("/policy?policy_id=instance1"), httpStatus, responseBody);
396 this.addPolicy("instance1", "type1", "service1", "ric1");
397 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
398 testErrorCode(restClient().get("/policy-status?policy_id=instance1"), httpStatus, responseBody);
400 // Check that empty response body is OK
401 a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
402 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
403 testErrorCode(restClient().get("/policy-status?policy_id=instance1"), httpStatus);
407 void testPutTypelessPolicy() throws Exception {
408 putService("service1");
409 addPolicyType("", "ric1");
410 String url = putPolicyUrl("service1", "ric1", "", "id1");
411 restClient().put(url, jsonString()).block();
413 String rsp = restClient().get("/policies").block();
414 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
415 assertThat(info.policies).hasSize(1);
416 PolicyInfo policyInfo = info.policies.iterator().next();
417 assertThat(policyInfo.policyId).isEqualTo("id1");
418 assertThat(policyInfo.policyTypeId).isEmpty();
422 void testRefuseToUpdatePolicy() throws Exception {
423 // Test that only the json can be changed for a already created policy
424 // In this case service is attempted to be changed
426 this.addRic("ricXXX");
427 this.addPolicy("instance1", "type1", "service1", "ric1");
428 this.addPolicy("instance2", "type1", "service1", "ricXXX");
430 // Try change ric1 -> ricXXX
431 String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
432 testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
436 void testGetPolicy() throws Exception {
437 String url = "/policy?policy_id=id";
438 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
440 String rsp = restClient().get(url).block();
441 assertThat(rsp).isEqualTo(policy.json());
444 policies.remove(policy);
445 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
450 void testDeletePolicy() throws Exception {
451 addPolicy("id", "typeName", "service1", "ric1");
452 assertThat(policies.size()).isEqualTo(1);
454 String url = "/policy?policy_id=id";
455 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
457 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
458 assertThat(policies.size()).isZero();
460 // Delete a non existing policy
461 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
465 void testGetPolicySchemas() throws Exception {
466 addPolicyType("type1", "ric1");
467 addPolicyType("type2", "ric2");
469 String url = "/policy-schemas";
470 String rsp = this.restClient().get(url).block();
471 assertThat(rsp).contains("type1") //
472 .contains("[{\"title\":\"type2\"}");
474 PolicySchemaList info = parseSchemas(rsp);
475 assertThat(info.schemas).hasSize(2);
477 url = "/policy-schemas?ric_id=ric1";
478 rsp = restClient().get(url).block();
479 assertThat(rsp).contains("type1");
480 info = parseSchemas(rsp);
481 assertThat(info.schemas).hasSize(1);
484 url = "/policy-schemas?policytype_id=type1";
485 rsp = restClient().get(url).block();
486 assertThat(rsp).contains("type1") //
489 // Both type and ric specified
490 url = "/policy-schemas?ric_id=ric1&policytype_id=type1";
491 rsp = restClient().get(url).block();
492 PolicySchemaList list = gson.fromJson(rsp, PolicySchemaList.class);
493 assertThat(list.schemas).hasSize(1);
495 url = "/policy-schemas?ric_id=ric1&policytype_id=type2";
496 rsp = restClient().get(url).block();
497 list = gson.fromJson(rsp, PolicySchemaList.class);
498 assertThat(list.schemas).isEmpty();
500 // Get schema for non existing RIC
501 url = "/policy-schemas?ric_id=ric1XXX";
502 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
504 // Get non existing schema
505 url = "/policy-schemas?policytype_id=type1XX";
506 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
509 String createPolicyTypesJson(String... types) {
510 List<String> list = new ArrayList<>();
511 Collections.addAll(list, types);
512 PolicyTypeIdList ids = new PolicyTypeIdList(list);
513 return gson.toJson(ids);
517 void testGetPolicyTypes() throws Exception {
518 addPolicyType("type1", "ric1");
519 addPolicyType("type2", "ric2");
521 String url = "/policy-types";
522 String rsp = restClient().get(url).block();
523 String expResp = createPolicyTypesJson("type2", "type1");
524 assertThat(rsp).isEqualTo(expResp);
526 url = "/policy-types?ric_id=ric1";
527 rsp = restClient().get(url).block();
528 expResp = createPolicyTypesJson("type1");
529 assertThat(rsp).isEqualTo(expResp);
531 // Get policy types for non existing RIC
532 url = "/policy-types?ric_id=ric1XXX";
533 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
537 void testGetPolicies() throws Exception {
538 addPolicy("id1", "type1", "service1");
540 String url = "/policies";
541 String rsp = restClient().get(url).block();
543 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
544 assertThat(info.policies).hasSize(1);
545 PolicyInfo policyInfo = info.policies.iterator().next();
546 assert (policyInfo.validate());
547 assertThat(policyInfo.policyId).isEqualTo("id1");
548 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
549 assertThat(policyInfo.serviceId).isEqualTo("service1");
553 void testGetPoliciesFilter() throws Exception {
554 addPolicy("id1", "type1", "service1");
555 addPolicy("id2", "type1", "service2");
556 addPolicy("id3", "type2", "service1");
558 String url = "/policies?policytype_id=type1";
559 String rsp = restClient().get(url).block();
561 assertThat(rsp).contains("id1") //
563 .doesNotContain("id3");
565 url = "/policies?policytype_id=type1&service_id=service2";
566 rsp = restClient().get(url).block();
568 assertThat(rsp).doesNotContain("id1") //
570 .doesNotContain("id3");
572 // Test get policies for non existing type
573 url = "/policies?policytype_id=type1XXX";
574 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
576 // Test get policies for non existing RIC
577 url = "/policies?ric_id=XXX";
578 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
582 void testGetPolicyIdsFilter() throws Exception {
583 addPolicy("id1", "type1", "service1", "ric1");
584 addPolicy("id2", "type1", "service2", "ric1");
585 addPolicy("id3", "type2", "service1", "ric1");
587 String url = "/policy-ids?policytype_id=type1";
588 String rsp = restClient().get(url).block();
590 assertThat(rsp).contains("id1") //
592 .doesNotContain("id3");
594 url = "/policy-ids?policytype_id=type1&service_id=service1&ric=ric1";
595 rsp = restClient().get(url).block();
596 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
597 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
599 // Test get policy ids for non existing type
600 url = "/policy-ids?policytype_id=type1XXX";
601 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
603 // Test get policy ids for non existing RIC
604 url = "/policy-ids?ric_id=XXX";
605 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
609 void testPutAndGetService() throws Exception {
611 String serviceName = "name";
612 putService(serviceName, 0, HttpStatus.CREATED);
613 putService(serviceName, 0, HttpStatus.OK);
616 String url = "/services?service_id=name";
617 String rsp = restClient().get(url).block();
618 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
619 assertThat(info.statusList).hasSize(1);
620 ServiceStatus status = info.statusList.iterator().next();
621 assertThat(status.keepAliveIntervalSeconds).isZero();
622 assertThat(status.serviceId).isEqualTo(serviceName);
626 rsp = restClient().get(url).block();
627 assertThat(rsp).as("Response contains service name").contains(serviceName);
631 url = "/services/keepalive?service_id=name";
632 ResponseEntity<?> entity = restClient().putForEntity(url).block();
633 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
636 assertThat(services.size()).isEqualTo(1);
637 url = "/services?service_id=name";
638 restClient().delete(url).block();
639 assertThat(services.size()).isZero();
641 // Keep alive, no registered service
642 testErrorCode(restClient().put("/services/keepalive?service_id=name", ""), HttpStatus.NOT_FOUND);
644 // PUT service with bad payload
645 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
646 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
647 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
649 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
650 HttpStatus.BAD_REQUEST, false);
652 // GET non existing service
653 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
657 void testServiceSupervision() throws Exception {
658 putService("service1", 1, HttpStatus.CREATED);
659 addPolicyType("type1", "ric1");
661 String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
662 final String policyBody = jsonString();
663 restClient().put(url, policyBody).block();
665 assertThat(policies.size()).isEqualTo(1);
666 assertThat(services.size()).isEqualTo(1);
668 // Timeout after ~1 second
669 await().untilAsserted(() -> assertThat(policies.size()).isZero());
670 assertThat(services.size()).isZero();
674 void testGetPolicyStatus() throws Exception {
675 addPolicy("id", "typeName", "service1", "ric1");
676 assertThat(policies.size()).isEqualTo(1);
678 String url = "/policy-status?policy_id=id";
679 String rsp = restClient().get(url).block();
680 assertThat(rsp).isEqualTo("OK");
682 // GET non existing policy status
683 url = "/policy-status?policy_id=XXX";
684 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
687 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
689 Policy policy = ImmutablePolicy.builder() //
691 .json(jsonString()) //
692 .ownerServiceId(service) //
693 .ric(rics.getRic(ric)) //
694 .type(addPolicyType(typeName, ric)) //
695 .lastModified(Instant.now()) //
696 .isTransient(false) //
698 policies.put(policy);
702 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
703 return addPolicy(id, typeName, service, "ric");
706 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
707 return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
710 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
711 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
713 String json = gson.toJson(service);
717 private void putService(String name) {
718 putService(name, 0, null);
721 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
722 String url = "/services";
723 String body = createServiceJson(name, keepAliveIntervalSeconds);
724 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
725 if (expectedStatus != null) {
726 assertEquals(expectedStatus, resp.getStatusCode(), "");
730 private String baseUrl() {
731 return "https://localhost:" + port + Consts.V2_API_ROOT;
734 private String jsonString() {
735 return "{\"servingCellNrcgi\":\"1\"}";
739 void testConcurrency() throws Exception {
740 final Instant startTime = Instant.now();
741 List<Thread> threads = new ArrayList<>();
742 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
743 a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
745 addPolicyType("type1", "ric");
746 addPolicyType("type2", "ric");
748 for (int i = 0; i < 10; ++i) {
749 AsyncRestClient restClient = restClient();
750 ConcurrencyTestRunnable test =
751 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
752 Thread thread = new Thread(test, "TestThread_" + i);
757 for (Thread t : threads) {
760 for (ConcurrencyTestRunnable test : tests) {
761 assertThat(test.isFailed()).isFalse();
763 assertThat(policies.size()).isZero();
764 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
767 private AsyncRestClient restClient(boolean useTrustValidation) {
768 WebClientConfig config = this.applicationConfig.getWebClientConfig();
769 config = ImmutableWebClientConfig.builder() //
770 .keyStoreType(config.keyStoreType()) //
771 .keyStorePassword(config.keyStorePassword()) //
772 .keyStore(config.keyStore()) //
773 .keyPassword(config.keyPassword()) //
774 .isTrustStoreUsed(useTrustValidation) //
775 .trustStore(config.trustStore()) //
776 .trustStorePassword(config.trustStorePassword()) //
779 return new AsyncRestClient(baseUrl(), config);
782 private AsyncRestClient restClient() {
783 return restClient(false);
786 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
787 testErrorCode(request, expStatus, "", true);
790 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
791 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
794 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
795 testErrorCode(request, expStatus, responseContains, true);
798 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
799 boolean expectApplicationProblemJsonMediaType) {
800 StepVerifier.create(request) //
801 .expectSubscription() //
803 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
807 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
808 boolean expectApplicationProblemJsonMediaType) {
809 assertTrue(throwable instanceof WebClientResponseException);
810 WebClientResponseException responseException = (WebClientResponseException) throwable;
811 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
812 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
813 if (expectApplicationProblemJsonMediaType) {
814 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
819 private MockA1Client getA1Client(String ricId) throws ServiceException {
820 return a1ClientFactory.getOrCreateA1Client(ricId);
823 private PolicyType createPolicyType(String policyTypeName) {
824 return ImmutablePolicyType.builder() //
825 .id(policyTypeName) //
826 .schema("{\"title\":\"" + policyTypeName + "\"}") //
830 private PolicyType addPolicyType(String policyTypeName, String ricId) {
831 PolicyType type = createPolicyType(policyTypeName);
832 policyTypes.put(type);
833 addRic(ricId).addSupportedPolicyType(type);
837 private Ric addRic(String ricId) {
838 return addRic(ricId, null);
841 private Ric addRic(String ricId, String managedElement) {
842 if (rics.get(ricId) != null) {
843 return rics.get(ricId);
845 List<String> mes = new ArrayList<>();
846 if (managedElement != null) {
847 mes.add(managedElement);
849 RicConfig conf = ImmutableRicConfig.builder() //
852 .managedElementIds(mes) //
853 .controllerName("") //
855 Ric ric = new Ric(conf);
856 ric.setState(Ric.RicState.AVAILABLE);
861 private static PolicySchemaList parseSchemas(String jsonString) {
862 return gson.fromJson(jsonString, PolicySchemaList.class);