2 * ========================LICENSE_START=================================
4 * ======================================================================
5 * Copyright (C) 2019-2020 Nordix Foundation. All rights reserved.
6 * ======================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ========================LICENSE_END===================================
21 package org.onap.ccsdk.oran.a1policymanagementservice.controllers.v2;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.Mockito.doReturn;
30 import com.google.gson.Gson;
31 import com.google.gson.GsonBuilder;
33 import java.io.FileNotFoundException;
34 import java.io.FileOutputStream;
35 import java.io.PrintStream;
36 import java.nio.charset.StandardCharsets;
37 import java.time.Duration;
38 import java.time.Instant;
39 import java.util.ArrayList;
40 import java.util.Collections;
41 import java.util.List;
43 import org.json.JSONObject;
44 import org.junit.jupiter.api.AfterEach;
45 import org.junit.jupiter.api.BeforeEach;
46 import org.junit.jupiter.api.Test;
47 import org.junit.jupiter.api.extension.ExtendWith;
48 import org.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
49 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
50 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableRicConfig;
51 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableWebClientConfig;
52 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
53 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
54 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
55 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
66 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
67 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
68 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
69 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.springframework.beans.factory.annotation.Autowired;
73 import org.springframework.boot.test.context.SpringBootTest;
74 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
75 import org.springframework.boot.test.context.TestConfiguration;
76 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
77 import org.springframework.boot.web.server.LocalServerPort;
78 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
79 import org.springframework.context.ApplicationContext;
80 import org.springframework.context.annotation.Bean;
81 import org.springframework.http.HttpStatus;
82 import org.springframework.http.MediaType;
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)
94 @TestPropertySource(properties = { //
95 "server.ssl.key-store=./config/keystore.jks", //
96 "app.webclient.trust-store=./config/truststore.jks"})
97 class ApplicationTest {
98 private static final Logger logger = LoggerFactory.getLogger(ApplicationTest.class);
101 ApplicationContext context;
107 private Policies policies;
110 private PolicyTypes policyTypes;
113 MockA1ClientFactory a1ClientFactory;
116 RicSupervision supervision;
119 ApplicationConfig applicationConfig;
124 private static Gson gson = new GsonBuilder() //
128 public static class MockApplicationConfig extends ApplicationConfig {
130 public String getLocalConfigurationFilePath() {
131 return ""; // No config file loaded for the test
136 * Overrides the BeanFactory.
139 static class TestBeanFactory {
140 private final PolicyTypes policyTypes = new PolicyTypes();
141 private final Services services = new Services();
142 private final Policies policies = new Policies();
143 MockA1ClientFactory a1ClientFactory = null;
146 public ApplicationConfig getApplicationConfig() {
147 return new MockApplicationConfig();
151 MockA1ClientFactory getA1ClientFactory() {
152 if (a1ClientFactory == null) {
153 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
155 return this.a1ClientFactory;
159 public PolicyTypes getPolicyTypes() {
160 return this.policyTypes;
164 Policies getPolicies() {
165 return this.policies;
169 Services getServices() {
170 return this.services;
174 public ServiceSupervision getServiceSupervision() {
175 Duration checkInterval = Duration.ofMillis(1);
176 return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
180 public ServletWebServerFactory servletContainer() {
181 return new TomcatServletWebServerFactory();
195 a1ClientFactory.reset();
199 void verifyNoRicLocks() {
200 for (Ric ric : this.rics.getRics()) {
201 ric.getLock().lockBlocking(LockType.EXCLUSIVE);
202 ric.getLock().unlockBlocking();
203 assertThat(ric.getLock().getLockCounter()).isZero();
204 assertThat(ric.getState()).isEqualTo(Ric.RicState.AVAILABLE);
210 void createApiDoc() throws FileNotFoundException {
211 String url = "https://localhost:" + this.port + "/v2/api-docs";
212 ResponseEntity<String> resp = restClient("", false).getForEntity(url).block();
213 assertThat(resp.getStatusCode()).isEqualTo(HttpStatus.OK);
214 String indented = (new JSONObject(resp.getBody())).toString(4);
215 try (PrintStream out = new PrintStream(new FileOutputStream("api/api_generated.json"))) {
221 void testGetRics() throws Exception {
223 this.addPolicyType("type1", "ric1");
224 String url = "/rics?policytype_id=type1";
225 String rsp = restClient().get(url).block();
226 assertThat(rsp).contains("ric1");
228 // nameless type for ORAN A1 1.1
230 this.addPolicyType("", "ric2");
231 url = "/rics?policytype_id=";
233 // This tests also validation of trusted certs restClient(true)
234 rsp = restClient(true).get(url).block();
235 assertThat(rsp).contains("ric2") //
236 .doesNotContain("ric1") //
237 .contains("AVAILABLE");
240 rsp = restClient().get("/rics").block();
241 assertThat(rsp).contains("ric2") //
244 // Non existing policy type
245 url = "/rics?policytype_id=XXXX";
246 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
250 void testSynchronization() throws Exception {
251 // Two polictypes will be put in the NearRT RICs
252 PolicyTypes nearRtRicPolicyTypes = new PolicyTypes();
253 nearRtRicPolicyTypes.put(createPolicyType("typeName"));
254 nearRtRicPolicyTypes.put(createPolicyType("typeName2"));
255 this.a1ClientFactory.setPolicyTypes(nearRtRicPolicyTypes);
257 // One type and one instance added to the Policy Management Service's storage
258 final String ric1Name = "ric1";
259 Ric ric1 = addRic(ric1Name);
260 Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
261 Ric ric2 = addRic("ric2");
263 getA1Client(ric1Name).putPolicy(policy2); // put it in the RIC (Near-RT RIC)
264 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
266 String policyId = "policyId";
267 Policy policy = addPolicy(policyId, "typeName", "service", ric1Name); // This should be created in the RIC
268 supervision.checkAllRics(); // The created policy should be put in the RIC
270 // Wait until synch is completed
271 waitForRicState(ric1Name, RicState.SYNCHRONIZING);
272 waitForRicState(ric1Name, RicState.AVAILABLE);
273 waitForRicState("ric2", RicState.AVAILABLE);
275 Policies ricPolicies = getA1Client(ric1Name).getPolicies();
276 assertThat(ricPolicies.size()).isEqualTo(1);
277 Policy ricPolicy = ricPolicies.get(policyId);
278 assertThat(ricPolicy.json()).isEqualTo(policy.json());
280 // Both types should be in the Policy Management Service's storage after the
282 assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
283 assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
287 void testGetRic() throws Exception {
288 String ricId = "ric1";
289 String managedElementId = "kista_1";
290 addRic(ricId, managedElementId);
292 String url = "/ric?managed_element_id=" + managedElementId;
293 String rsp = restClient().get(url).block();
294 RicInfo ricInfo = gson.fromJson(rsp, RicInfo.class);
295 assertThat(ricInfo.ricId).isEqualTo(ricId);
297 url = "/ric?ric_id=" + ricId;
298 rsp = restClient().get(url).block();
299 ricInfo = gson.fromJson(rsp, RicInfo.class);
300 assertThat(ricInfo.ricId).isEqualTo(ricId);
302 // test GET RIC for ManagedElement that does not exist
303 url = "/ric?managed_element_id=" + "junk";
304 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
307 testErrorCode(restClient().get(url), HttpStatus.BAD_REQUEST);
310 private String putPolicyUrl(String serviceName, String ricId, String policyTypeName, String policyInstanceId,
311 boolean isTransient) {
313 if (policyTypeName.isEmpty()) {
314 url = "/policy?policy_id=" + policyInstanceId + "&ric_id=" + ricId + "&service_id=" + serviceName;
316 url = "/policy?policy_id=" + policyInstanceId + "&ric_id=" + ricId + "&service_id=" + serviceName
317 + "&policytype_id=" + policyTypeName;
320 url += "&transient=true";
325 private String putPolicyUrl(String serviceName, String ricId, String policyTypeName, String policyInstanceId) {
326 return putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId, false);
330 void testPutPolicy() throws Exception {
331 String serviceName = "service1";
332 String ricId = "ric1";
333 String policyTypeName = "type1";
334 String policyInstanceId = "instance1";
336 putService(serviceName);
337 addPolicyType(policyTypeName, ricId);
339 // PUT a transient policy
340 String url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId, true);
341 final String policyBody = jsonString();
342 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
344 restClient().put(url, policyBody).block();
346 Policy policy = policies.getPolicy(policyInstanceId);
347 assertThat(policy).isNotNull();
348 assertThat(policy.id()).isEqualTo(policyInstanceId);
349 assertThat(policy.ownerServiceId()).isEqualTo(serviceName);
350 assertThat(policy.ric().id()).isEqualTo("ric1");
351 assertThat(policy.isTransient()).isTrue();
353 // Put a non transient policy
354 url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId);
355 restClient().put(url, policyBody).block();
356 policy = policies.getPolicy(policyInstanceId);
357 assertThat(policy.isTransient()).isFalse();
360 String rsp = restClient().get(url).block();
361 assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
363 url = "/policy?policy_id=" + policyInstanceId;
364 rsp = restClient().get(url).block();
365 assertThat(rsp).isEqualTo(policyBody);
367 // Test of error codes
368 url = putPolicyUrl(serviceName, ricId + "XX", policyTypeName, policyInstanceId);
369 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
371 url = putPolicyUrl(serviceName, ricId, policyTypeName + "XX", policyInstanceId);
372 addPolicyType(policyTypeName + "XX", "otherRic");
373 testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
375 url = putPolicyUrl(serviceName, ricId, policyTypeName, policyInstanceId);
376 this.rics.getRic(ricId).setState(Ric.RicState.SYNCHRONIZING);
377 testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
378 this.rics.getRic(ricId).setState(Ric.RicState.AVAILABLE);
383 * Test that HttpStatus and body from failing REST call to A1 is passed on to
386 * @throws ServiceException
388 void testErrorFromRic() throws ServiceException {
389 putService("service1");
390 addPolicyType("type1", "ric1");
392 String url = putPolicyUrl("service1", "ric1", "type1", "id1");
393 MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
394 HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
395 String responseBody = "Refused";
396 byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
398 WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
399 responseBodyBytes, StandardCharsets.UTF_8, null);
400 doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
403 testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
406 this.addPolicy("instance1", "type1", "service1", "ric1");
407 doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
408 testErrorCode(restClient().delete("/policy?policy_id=instance1"), httpStatus, responseBody);
411 this.addPolicy("instance1", "type1", "service1", "ric1");
412 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
413 testErrorCode(restClient().get("/policy-status?policy_id=instance1"), httpStatus, responseBody);
415 // Check that empty response body is OK
416 a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
417 doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
418 testErrorCode(restClient().get("/policy-status?policy_id=instance1"), httpStatus);
422 void testPutTypelessPolicy() throws Exception {
423 putService("service1");
424 addPolicyType("", "ric1");
425 String url = putPolicyUrl("service1", "ric1", "", "id1");
426 restClient().put(url, jsonString()).block();
428 String rsp = restClient().get("/policies").block();
429 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
430 assertThat(info.policies).hasSize(1);
431 PolicyInfo policyInfo = info.policies.iterator().next();
432 assertThat(policyInfo.policyId).isEqualTo("id1");
433 assertThat(policyInfo.policyTypeId).isEmpty();
437 void testRefuseToUpdatePolicy() throws Exception {
438 // Test that only the json can be changed for a already created policy
439 // In this case service is attempted to be changed
441 this.addRic("ricXXX");
442 this.addPolicy("instance1", "type1", "service1", "ric1");
443 this.addPolicy("instance2", "type1", "service1", "ricXXX");
445 // Try change ric1 -> ricXXX
446 String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
447 testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
451 void testGetPolicy() throws Exception {
452 String url = "/policy?policy_id=id";
453 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
455 String rsp = restClient().get(url).block();
456 assertThat(rsp).isEqualTo(policy.json());
459 policies.remove(policy);
460 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
465 void testDeletePolicy() throws Exception {
466 addPolicy("id", "typeName", "service1", "ric1");
467 assertThat(policies.size()).isEqualTo(1);
469 String url = "/policy?policy_id=id";
470 ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
472 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
473 assertThat(policies.size()).isZero();
475 // Delete a non existing policy
476 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
480 void testGetPolicySchemas() throws Exception {
481 addPolicyType("type1", "ric1");
482 addPolicyType("type2", "ric2");
484 waitForRicState("ric1", RicState.AVAILABLE);
485 waitForRicState("ric2", RicState.AVAILABLE);
487 String url = "/policy-schemas";
488 String rsp = this.restClient().get(url).block();
489 assertThat(rsp).contains("type1") //
490 .contains("{\"title\":\"type2\"}");
492 PolicySchemaList info = parseSchemas(rsp);
493 assertThat(info.schemas).hasSize(2);
495 url = "/policy-schemas?ric_id=ric1";
496 rsp = restClient().get(url).block();
497 assertThat(rsp).contains("type1");
498 info = parseSchemas(rsp);
499 assertThat(info.schemas).hasSize(1);
502 url = "/policy-schemas?policytype_id=type1";
503 rsp = restClient().get(url).block();
504 assertThat(rsp).contains("type1") //
507 // Both type and ric specified
508 url = "/policy-schemas?ric_id=ric1&policytype_id=type1";
509 rsp = restClient().get(url).block();
510 PolicySchemaList list = gson.fromJson(rsp, PolicySchemaList.class);
511 assertThat(list.schemas).hasSize(1);
513 url = "/policy-schemas?ric_id=ric1&policytype_id=type2";
514 rsp = restClient().get(url).block();
515 list = gson.fromJson(rsp, PolicySchemaList.class);
516 assertThat(list.schemas).isEmpty();
518 // Get schema for non existing RIC
519 url = "/policy-schemas?ric_id=ric1XXX";
520 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
522 // Get non existing schema
523 url = "/policy-schemas?policytype_id=type1XX";
524 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
527 String createPolicyTypesJson(String... types) {
528 List<String> list = new ArrayList<>();
529 Collections.addAll(list, types);
530 PolicyTypeIdList ids = new PolicyTypeIdList(list);
531 return gson.toJson(ids);
535 void testGetPolicyTypes() throws Exception {
536 addPolicyType("type1", "ric1");
537 addPolicyType("type2", "ric2");
539 String url = "/policy-types";
540 String rsp = restClient().get(url).block();
541 String expResp = createPolicyTypesJson("type2", "type1");
542 assertThat(rsp).isEqualTo(expResp);
544 url = "/policy-types?ric_id=ric1";
545 rsp = restClient().get(url).block();
546 expResp = createPolicyTypesJson("type1");
547 assertThat(rsp).isEqualTo(expResp);
549 // Get policy types for non existing RIC
550 url = "/policy-types?ric_id=ric1XXX";
551 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
555 void testGetPolicies() throws Exception {
556 addPolicy("id1", "type1", "service1");
558 String url = "/policies";
559 String rsp = restClient().get(url).block();
561 PolicyInfoList info = gson.fromJson(rsp, PolicyInfoList.class);
562 assertThat(info.policies).hasSize(1);
563 PolicyInfo policyInfo = info.policies.iterator().next();
564 assert (policyInfo.validate());
565 assertThat(policyInfo.policyId).isEqualTo("id1");
566 assertThat(policyInfo.policyTypeId).isEqualTo("type1");
567 assertThat(policyInfo.serviceId).isEqualTo("service1");
571 void testGetPoliciesFilter() throws Exception {
572 addPolicy("id1", "type1", "service1");
573 addPolicy("id2", "type1", "service2");
574 addPolicy("id3", "type2", "service1");
576 String url = "/policies?policytype_id=type1";
577 String rsp = restClient().get(url).block();
579 assertThat(rsp).contains("id1") //
581 .doesNotContain("id3");
583 url = "/policies?policytype_id=type1&service_id=service2";
584 rsp = restClient().get(url).block();
586 assertThat(rsp).doesNotContain("id1") //
588 .doesNotContain("id3");
590 // Test get policies for non existing type
591 url = "/policies?policytype_id=type1XXX";
592 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
594 // Test get policies for non existing RIC
595 url = "/policies?ric_id=XXX";
596 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
600 void testGetPolicyIdsFilter() throws Exception {
601 addPolicy("id1", "type1", "service1", "ric1");
602 addPolicy("id2", "type1", "service2", "ric1");
603 addPolicy("id3", "type2", "service1", "ric1");
605 String url = "/policy-ids?policytype_id=type1";
606 String rsp = restClient().get(url).block();
608 assertThat(rsp).contains("id1") //
610 .doesNotContain("id3");
612 url = "/policy-ids?policytype_id=type1&service_id=service1&ric=ric1";
613 rsp = restClient().get(url).block();
614 PolicyIdList respList = gson.fromJson(rsp, PolicyIdList.class);
615 assertThat(respList.policyIds.iterator().next()).isEqualTo("id1");
617 // Test get policy ids for non existing type
618 url = "/policy-ids?policytype_id=type1XXX";
619 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
621 // Test get policy ids for non existing RIC
622 url = "/policy-ids?ric_id=XXX";
623 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
627 void testPutAndGetService() throws Exception {
629 String serviceName = "name";
630 putService(serviceName, 0, HttpStatus.CREATED);
631 putService(serviceName, 0, HttpStatus.OK);
634 String url = "/services?service_id=name";
635 String rsp = restClient().get(url).block();
636 ServiceStatusList info = gson.fromJson(rsp, ServiceStatusList.class);
637 assertThat(info.statusList).hasSize(1);
638 ServiceStatus status = info.statusList.iterator().next();
639 assertThat(status.keepAliveIntervalSeconds).isZero();
640 assertThat(status.serviceId).isEqualTo(serviceName);
644 rsp = restClient().get(url).block();
645 assertThat(rsp).as("Response contains service name").contains(serviceName);
649 url = "/services/keepalive?service_id=name";
650 ResponseEntity<?> entity = restClient().putForEntity(url).block();
651 assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
654 assertThat(services.size()).isEqualTo(1);
655 url = "/services?service_id=name";
656 restClient().delete(url).block();
657 assertThat(services.size()).isZero();
659 // Keep alive, no registered service
660 testErrorCode(restClient().put("/services/keepalive?service_id=name", ""), HttpStatus.NOT_FOUND);
662 // PUT service with bad payload
663 testErrorCode(restClient().put("/services", "crap"), HttpStatus.BAD_REQUEST, false);
664 testErrorCode(restClient().put("/services", "{}"), HttpStatus.BAD_REQUEST, false);
665 testErrorCode(restClient().put("/services", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST,
667 testErrorCode(restClient().put("/services", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
668 HttpStatus.BAD_REQUEST, false);
670 // GET non existing service
671 testErrorCode(restClient().get("/services?service_id=XXX"), HttpStatus.NOT_FOUND);
675 void testServiceSupervision() throws Exception {
676 putService("service1", 1, HttpStatus.CREATED);
677 addPolicyType("type1", "ric1");
679 String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
680 final String policyBody = jsonString();
681 restClient().put(url, policyBody).block();
683 assertThat(policies.size()).isEqualTo(1);
684 assertThat(services.size()).isEqualTo(1);
686 // Timeout after ~1 second
687 await().untilAsserted(() -> assertThat(policies.size()).isZero());
688 assertThat(services.size()).isZero();
692 void testGetPolicyStatus() throws Exception {
693 addPolicy("id", "typeName", "service1", "ric1");
694 assertThat(policies.size()).isEqualTo(1);
696 String url = "/policy-status?policy_id=id";
697 String rsp = restClient().get(url).block();
698 assertThat(rsp).isEqualTo("OK");
700 // GET non existing policy status
701 url = "/policy-status?policy_id=XXX";
702 testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
705 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
707 Policy policy = ImmutablePolicy.builder() //
709 .json(jsonString()) //
710 .ownerServiceId(service) //
711 .ric(rics.getRic(ric)) //
712 .type(addPolicyType(typeName, ric)) //
713 .lastModified(Instant.now()) //
714 .isTransient(false) //
716 policies.put(policy);
720 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
721 return addPolicy(id, typeName, service, "ric");
724 private String createServiceJson(String name, long keepAliveIntervalSeconds) {
725 return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
728 private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
729 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
731 String json = gson.toJson(service);
735 private void putService(String name) {
736 putService(name, 0, null);
739 private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
740 String url = "/services";
741 String body = createServiceJson(name, keepAliveIntervalSeconds);
742 ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
743 if (expectedStatus != null) {
744 assertEquals(expectedStatus, resp.getStatusCode(), "");
748 private String jsonString() {
749 return "{\"servingCellNrcgi\":\"1\"}";
753 void testConcurrency() throws Exception {
754 final Instant startTime = Instant.now();
755 List<Thread> threads = new ArrayList<>();
756 List<ConcurrencyTestRunnable> tests = new ArrayList<>();
757 a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
759 addPolicyType("type1", "ric");
760 addPolicyType("type2", "ric");
762 for (int i = 0; i < 10; ++i) {
763 AsyncRestClient restClient = restClient();
764 ConcurrencyTestRunnable test =
765 new ConcurrencyTestRunnable(restClient, supervision, a1ClientFactory, rics, policyTypes);
766 Thread thread = new Thread(test, "TestThread_" + i);
771 for (Thread t : threads) {
774 for (ConcurrencyTestRunnable test : tests) {
775 assertThat(test.isFailed()).isFalse();
777 assertThat(policies.size()).isZero();
778 logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
781 private AsyncRestClient restClient(String baseUrl, boolean useTrustValidation) {
782 WebClientConfig config = this.applicationConfig.getWebClientConfig();
783 config = ImmutableWebClientConfig.builder() //
784 .keyStoreType(config.keyStoreType()) //
785 .keyStorePassword(config.keyStorePassword()) //
786 .keyStore(config.keyStore()) //
787 .keyPassword(config.keyPassword()) //
788 .isTrustStoreUsed(useTrustValidation) //
789 .trustStore(config.trustStore()) //
790 .trustStorePassword(config.trustStorePassword()) //
793 return new AsyncRestClient(baseUrl, config);
796 private AsyncRestClient restClient(boolean useTrustValidation) {
797 String baseUrl = "https://localhost:" + port + Consts.V2_API_ROOT;
798 return restClient(baseUrl, useTrustValidation);
801 private AsyncRestClient restClient() {
802 return restClient(false);
805 private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
806 testErrorCode(request, expStatus, "", true);
809 private void testErrorCode(Mono<?> request, HttpStatus expStatus, boolean expectApplicationProblemJsonMediaType) {
810 testErrorCode(request, expStatus, "", expectApplicationProblemJsonMediaType);
813 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
814 testErrorCode(request, expStatus, responseContains, true);
817 private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains,
818 boolean expectApplicationProblemJsonMediaType) {
819 StepVerifier.create(request) //
820 .expectSubscription() //
822 t -> checkWebClientError(t, expStatus, responseContains, expectApplicationProblemJsonMediaType)) //
826 private void waitForRicState(String ricId, RicState state) throws ServiceException {
827 Ric ric = rics.getRic(ricId);
828 await().untilAsserted(() -> state.equals(ric.getState()));
831 private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains,
832 boolean expectApplicationProblemJsonMediaType) {
833 assertTrue(throwable instanceof WebClientResponseException);
834 WebClientResponseException responseException = (WebClientResponseException) throwable;
835 assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
836 assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
837 if (expectApplicationProblemJsonMediaType) {
838 assertThat(responseException.getHeaders().getContentType()).isEqualTo(MediaType.APPLICATION_PROBLEM_JSON);
843 private MockA1Client getA1Client(String ricId) throws ServiceException {
844 return a1ClientFactory.getOrCreateA1Client(ricId);
847 private PolicyType createPolicyType(String policyTypeName) {
848 return ImmutablePolicyType.builder() //
849 .id(policyTypeName) //
850 .schema("{\"title\":\"" + policyTypeName + "\"}") //
854 private PolicyType addPolicyType(String policyTypeName, String ricId) {
855 PolicyType type = createPolicyType(policyTypeName);
856 policyTypes.put(type);
857 addRic(ricId).addSupportedPolicyType(type);
861 private Ric addRic(String ricId) {
862 return addRic(ricId, null);
865 private Ric addRic(String ricId, String managedElement) {
866 if (rics.get(ricId) != null) {
867 return rics.get(ricId);
869 List<String> mes = new ArrayList<>();
870 if (managedElement != null) {
871 mes.add(managedElement);
873 RicConfig conf = ImmutableRicConfig.builder() //
876 .managedElementIds(mes) //
877 .controllerName("") //
879 Ric ric = new Ric(conf);
880 ric.setState(Ric.RicState.AVAILABLE);
885 private static PolicySchemaList parseSchemas(String jsonString) {
886 return gson.fromJson(jsonString, PolicySchemaList.class);