971f358ce08c9e83384d22edba1a754587c5edd5
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
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===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice;
22
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;
29
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;
35
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;
41
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.onap.ccsdk.oran.a1policymanagementservice.clients.AsyncRestClient;
47 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ApplicationConfig;
48 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableRicConfig;
49 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableWebClientConfig;
50 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.RicConfig;
51 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.WebClientConfig;
52 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v1.PolicyInfo;
53 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v1.ServiceRegistrationInfo;
54 import org.onap.ccsdk.oran.a1policymanagementservice.controllers.v1.ServiceStatus;
55 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
56 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicy;
57 import org.onap.ccsdk.oran.a1policymanagementservice.repository.ImmutablePolicyType;
58 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Lock.LockType;
59 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
60 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
61 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
62 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyTypes;
63 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
64 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric.RicState;
65 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
66 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Services;
67 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.RicSupervision;
68 import org.onap.ccsdk.oran.a1policymanagementservice.tasks.ServiceSupervision;
69 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1Client;
70 import org.onap.ccsdk.oran.a1policymanagementservice.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;
87
88 import reactor.core.publisher.Mono;
89 import reactor.test.StepVerifier;
90 import reactor.util.annotation.Nullable;
91
92 @ExtendWith(SpringExtension.class)
93 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
94 @TestPropertySource(
95     properties = { //
96         "server.ssl.key-store=./config/keystore.jks", //
97         "app.webclient.trust-store=./config/truststore.jks"})
98 class ApplicationTestV1 {
99     private static final Logger logger = LoggerFactory.getLogger(ApplicationTestV1.class);
100
101     @Autowired
102     ApplicationContext context;
103
104     @Autowired
105     private Rics rics;
106
107     @Autowired
108     private Policies policies;
109
110     @Autowired
111     private PolicyTypes policyTypes;
112
113     @Autowired
114     MockA1ClientFactory a1ClientFactory;
115
116     @Autowired
117     RicSupervision supervision;
118
119     @Autowired
120     ApplicationConfig applicationConfig;
121
122     @Autowired
123     Services services;
124
125     private static Gson gson = new GsonBuilder() //
126         .serializeNulls() //
127         .create(); //
128
129     public static class MockApplicationConfig extends ApplicationConfig {
130         @Override
131         public String getLocalConfigurationFilePath() {
132             return ""; // No config file loaded for the test
133         }
134     }
135
136     /**
137      * Overrides the BeanFactory.
138      */
139     @TestConfiguration
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;
145
146         @Bean
147         public ApplicationConfig getApplicationConfig() {
148             return new MockApplicationConfig();
149         }
150
151         @Bean
152         MockA1ClientFactory getA1ClientFactory() {
153             if (a1ClientFactory == null) {
154                 this.a1ClientFactory = new MockA1ClientFactory(this.policyTypes);
155             }
156             return this.a1ClientFactory;
157         }
158
159         @Bean
160         public PolicyTypes getPolicyTypes() {
161             return this.policyTypes;
162         }
163
164         @Bean
165         Policies getPolicies() {
166             return this.policies;
167         }
168
169         @Bean
170         Services getServices() {
171             return this.services;
172         }
173
174         @Bean
175         public ServiceSupervision getServiceSupervision() {
176             Duration checkInterval = Duration.ofMillis(1);
177             return new ServiceSupervision(this.services, this.policies, this.getA1ClientFactory(), checkInterval);
178         }
179
180         @Bean
181         public ServletWebServerFactory servletContainer() {
182             return new TomcatServletWebServerFactory();
183         }
184
185     }
186
187     @LocalServerPort
188     private int port;
189
190     @BeforeEach
191     void reset() {
192         rics.clear();
193         policies.clear();
194         policyTypes.clear();
195         services.clear();
196         a1ClientFactory.reset();
197     }
198
199     @AfterEach
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);
206         }
207     }
208
209     @Test
210     void testGetRics() throws Exception {
211         addRic("ric1");
212         this.addPolicyType("type1", "ric1");
213         String url = "/rics?policyType=type1";
214         String rsp = restClient().get(url).block();
215         assertThat(rsp).contains("ric1");
216
217         // nameless type for ORAN A1 1.1
218         addRic("ric2");
219         this.addPolicyType("", "ric2");
220         url = "/rics?policyType=";
221
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");
227
228         // All RICs
229         rsp = restClient().get("/rics").block();
230         assertThat(rsp).contains("ric2") //
231             .contains("ric1");
232
233         // Non existing policy type
234         url = "/rics?policyType=XXXX";
235         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
236     }
237
238     @Test
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);
245
246         // One type and one instance added to the Policy Management Service's storage
247         final String ric1Name = "ric1";
248         Ric ric1 = addRic(ric1Name);
249         Policy policy2 = addPolicy("policyId2", "typeName", "service", ric1Name);
250         Ric ric2 = addRic("ric2");
251
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
254
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
258
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()));
263
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());
268
269         // Both types should be in the Policy Management Service's storage after the
270         // synch
271         assertThat(ric1.getSupportedPolicyTypes()).hasSize(2);
272         assertThat(ric2.getSupportedPolicyTypes()).hasSize(2);
273     }
274
275     @Test
276     void testGetRicForManagedElement_thenReturnCorrectRic() throws Exception {
277         String ricName = "ric1";
278         String managedElementId = "kista_1";
279         addRic(ricName, managedElementId);
280
281         String url = "/ric?managedElementId=" + managedElementId;
282         String rsp = restClient().get(url).block();
283         assertThat(rsp).isEqualTo(ricName);
284
285         // test GET RIC for ManagedElement that does not exist
286         url = "/ric?managedElementId=" + "junk";
287         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
288     }
289
290     private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId,
291         boolean isTransient) {
292         String url;
293         if (policyTypeName.isEmpty()) {
294             url = "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName;
295         } else {
296             url = "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName + "&type="
297                 + policyTypeName;
298         }
299         if (isTransient) {
300             url += "&transient=true";
301         }
302         return url;
303     }
304
305     private String putPolicyUrl(String serviceName, String ricName, String policyTypeName, String policyInstanceId) {
306         return putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId, false);
307     }
308
309     @Test
310     void testPutPolicy() throws Exception {
311         String serviceName = "service1";
312         String ricName = "ric1";
313         String policyTypeName = "type1";
314         String policyInstanceId = "instance1";
315
316         putService(serviceName);
317         addPolicyType(policyTypeName, ricName);
318
319         // PUT a transient policy
320         String url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId, true);
321         final String policyBody = jsonString();
322         this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
323
324         restClient().put(url, policyBody).block();
325
326         Policy policy = policies.getPolicy(policyInstanceId);
327         assertThat(policy).isNotNull();
328         assertThat(policy.id()).isEqualTo(policyInstanceId);
329         assertThat(policy.ownerServiceId()).isEqualTo(serviceName);
330         assertThat(policy.ric().id()).isEqualTo("ric1");
331         assertThat(policy.isTransient()).isTrue();
332
333         // Put a non transient policy
334         url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
335         restClient().put(url, policyBody).block();
336         policy = policies.getPolicy(policyInstanceId);
337         assertThat(policy.isTransient()).isFalse();
338
339         url = "/policies";
340         String rsp = restClient().get(url).block();
341         assertThat(rsp).as("Response contains policy instance ID.").contains(policyInstanceId);
342
343         url = "/policy?id=" + policyInstanceId;
344         rsp = restClient().get(url).block();
345         assertThat(rsp).isEqualTo(policyBody);
346
347         // Test of error codes
348         url = putPolicyUrl(serviceName, ricName + "XX", policyTypeName, policyInstanceId);
349         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
350
351         url = putPolicyUrl(serviceName, ricName, policyTypeName + "XX", policyInstanceId);
352         addPolicyType(policyTypeName + "XX", "otherRic");
353         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
354
355         url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
356         this.rics.getRic(ricName).setState(Ric.RicState.SYNCHRONIZING);
357         testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
358         this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
359     }
360
361     @Test
362     /**
363      * Test that HttpStatus and body from failing REST call to A1 is passed on to
364      * the caller.
365      *
366      * @throws ServiceException
367      */
368     void testErrorFromRic() throws ServiceException {
369         putService("service1");
370         addPolicyType("type1", "ric1");
371
372         String url = putPolicyUrl("service1", "ric1", "type1", "id1");
373         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
374         HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
375         String responseBody = "Refused";
376         byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
377
378         WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
379             responseBodyBytes, StandardCharsets.UTF_8, null);
380         doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
381
382         // PUT Policy
383         testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
384
385         // DELETE POLICY
386         this.addPolicy("instance1", "type1", "service1", "ric1");
387         doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
388         testErrorCode(restClient().delete("/policy?id=instance1"), httpStatus, responseBody);
389
390         // GET STATUS
391         this.addPolicy("instance1", "type1", "service1", "ric1");
392         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
393         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus, responseBody);
394
395         // Check that empty response body is OK
396         a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
397         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
398         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus);
399     }
400
401     @Test
402     void testPutTypelessPolicy() throws Exception {
403         putService("service1");
404         addPolicyType("", "ric1");
405         String url = putPolicyUrl("service1", "ric1", "", "id1");
406         restClient().put(url, jsonString()).block();
407
408         String rsp = restClient().get("/policies").block();
409         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
410         assertThat(info).hasSize(1);
411         PolicyInfo policyInfo = info.get(0);
412         assertThat(policyInfo.id).isEqualTo("id1");
413         assertThat(policyInfo.type).isEmpty();
414     }
415
416     @Test
417     void testRefuseToUpdatePolicy() throws Exception {
418         // Test that only the json can be changed for a already created policy
419         // In this case service is attempted to be changed
420         this.addRic("ric1");
421         this.addRic("ricXXX");
422         this.addPolicy("instance1", "type1", "service1", "ric1");
423         this.addPolicy("instance2", "type1", "service1", "ricXXX");
424
425         // Try change ric1 -> ricXXX
426         String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
427         testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
428     }
429
430     @Test
431     void testGetPolicy() throws Exception {
432         String url = "/policy?id=id";
433         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
434         {
435             String rsp = restClient().get(url).block();
436             assertThat(rsp).isEqualTo(policy.json());
437         }
438         {
439             policies.remove(policy);
440             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
441         }
442     }
443
444     @Test
445     void testDeletePolicy() throws Exception {
446         addPolicy("id", "typeName", "service1", "ric1");
447         assertThat(policies.size()).isEqualTo(1);
448
449         String url = "/policy?id=id";
450         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
451
452         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
453         assertThat(policies.size()).isZero();
454
455         // Delete a non existing policy
456         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
457     }
458
459     @Test
460     void testGetPolicySchemas() throws Exception {
461         addPolicyType("type1", "ric1");
462         addPolicyType("type2", "ric2");
463
464         String url = "/policy_schemas";
465         String rsp = this.restClient().get(url).block();
466         assertThat(rsp).contains("type1") //
467             .contains("[{\"title\":\"type2\"}");
468
469         List<String> info = parseSchemas(rsp);
470         assertThat(info).hasSize(2);
471
472         url = "/policy_schemas?ric=ric1";
473         rsp = restClient().get(url).block();
474         assertThat(rsp).contains("type1");
475         info = parseSchemas(rsp);
476         assertThat(info).hasSize(1);
477
478         // Get schema for non existing RIC
479         url = "/policy_schemas?ric=ric1XXX";
480         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
481     }
482
483     @Test
484     void testGetPolicySchema() throws Exception {
485         addPolicyType("type1", "ric1");
486         addPolicyType("type2", "ric2");
487
488         String url = "/policy_schema?id=type1";
489         String rsp = restClient().get(url).block();
490         logger.info(rsp);
491         assertThat(rsp).contains("type1") //
492             .contains("title");
493
494         // Get non existing schema
495         url = "/policy_schema?id=type1XX";
496         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
497     }
498
499     @Test
500     void testGetPolicyTypes() throws Exception {
501         addPolicyType("type1", "ric1");
502         addPolicyType("type2", "ric2");
503
504         String url = "/policy_types";
505         String rsp = restClient().get(url).block();
506         assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
507
508         url = "/policy_types?ric=ric1";
509         rsp = restClient().get(url).block();
510         assertThat(rsp).isEqualTo("[\"type1\"]");
511
512         // Get policy types for non existing RIC
513         url = "/policy_types?ric=ric1XXX";
514         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
515     }
516
517     @Test
518     void testGetPolicies() throws Exception {
519         addPolicy("id1", "type1", "service1");
520
521         String url = "/policies";
522         String rsp = restClient().get(url).block();
523         logger.info(rsp);
524         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
525         assertThat(info).hasSize(1);
526         PolicyInfo policyInfo = info.get(0);
527         assert (policyInfo.validate());
528         assertThat(policyInfo.id).isEqualTo("id1");
529         assertThat(policyInfo.type).isEqualTo("type1");
530         assertThat(policyInfo.service).isEqualTo("service1");
531     }
532
533     @Test
534     void testGetPoliciesFilter() throws Exception {
535         addPolicy("id1", "type1", "service1");
536         addPolicy("id2", "type1", "service2");
537         addPolicy("id3", "type2", "service1");
538
539         String url = "/policies?type=type1";
540         String rsp = restClient().get(url).block();
541         logger.info(rsp);
542         assertThat(rsp).contains("id1") //
543             .contains("id2") //
544             .doesNotContain("id3");
545
546         url = "/policies?type=type1&service=service2";
547         rsp = restClient().get(url).block();
548         logger.info(rsp);
549         assertThat(rsp).doesNotContain("id1") //
550             .contains("id2") //
551             .doesNotContain("id3");
552
553         // Test get policies for non existing type
554         url = "/policies?type=type1XXX";
555         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
556
557         // Test get policies for non existing RIC
558         url = "/policies?ric=XXX";
559         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
560     }
561
562     @Test
563     void testGetPolicyIdsFilter() throws Exception {
564         addPolicy("id1", "type1", "service1", "ric1");
565         addPolicy("id2", "type1", "service2", "ric1");
566         addPolicy("id3", "type2", "service1", "ric1");
567
568         String url = "/policy_ids?type=type1";
569         String rsp = restClient().get(url).block();
570         logger.info(rsp);
571         assertThat(rsp).contains("id1") //
572             .contains("id2") //
573             .doesNotContain("id3");
574
575         url = "/policy_ids?type=type1&service=service1&ric=ric1";
576         rsp = restClient().get(url).block();
577         assertThat(rsp).isEqualTo("[\"id1\"]");
578
579         // Test get policy ids for non existing type
580         url = "/policy_ids?type=type1XXX";
581         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
582
583         // Test get policy ids for non existing RIC
584         url = "/policy_ids?ric=XXX";
585         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
586     }
587
588     @Test
589     void testPutAndGetService() throws Exception {
590         // PUT
591         String serviceName = "name";
592         putService(serviceName, 0, HttpStatus.CREATED);
593         putService(serviceName, 0, HttpStatus.OK);
594
595         // GET one service
596         String url = "/services?name=name";
597         String rsp = restClient().get(url).block();
598         List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
599         assertThat(info).hasSize(1);
600         ServiceStatus status = info.iterator().next();
601         assertThat(status.keepAliveIntervalSeconds).isZero();
602         assertThat(status.serviceName).isEqualTo(serviceName);
603
604         // GET (all)
605         url = "/services";
606         rsp = restClient().get(url).block();
607         assertThat(rsp).as("Response contains service name").contains(serviceName);
608         logger.info(rsp);
609
610         // Keep alive
611         url = "/services/keepalive?name=name";
612         ResponseEntity<String> entity = restClient().putForEntity(url).block();
613         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
614
615         // DELETE service
616         assertThat(services.size()).isEqualTo(1);
617         url = "/services?name=name";
618         restClient().delete(url).block();
619         assertThat(services.size()).isZero();
620
621         // Keep alive, no registered service
622         testErrorCode(restClient().put("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
623
624         // PUT servive with bad payload
625         testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
626         testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
627         testErrorCode(restClient().put("/service", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST);
628         testErrorCode(restClient().put("/service", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
629             HttpStatus.BAD_REQUEST);
630
631         // GET non existing service
632         testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
633     }
634
635     @Test
636     void testServiceSupervision() throws Exception {
637         putService("service1", 1, HttpStatus.CREATED);
638         addPolicyType("type1", "ric1");
639
640         String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
641         final String policyBody = jsonString();
642         restClient().put(url, policyBody).block();
643
644         assertThat(policies.size()).isEqualTo(1);
645         assertThat(services.size()).isEqualTo(1);
646
647         // Timeout after ~1 second
648         await().untilAsserted(() -> assertThat(policies.size()).isZero());
649         assertThat(services.size()).isZero();
650     }
651
652     @Test
653     void testGetPolicyStatus() throws Exception {
654         addPolicy("id", "typeName", "service1", "ric1");
655         assertThat(policies.size()).isEqualTo(1);
656
657         String url = "/policy_status?id=id";
658         String rsp = restClient().get(url).block();
659         assertThat(rsp).isEqualTo("OK");
660
661         // GET non existing policy status
662         url = "/policy_status?id=XXX";
663         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
664     }
665
666     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
667         addRic(ric);
668         Policy policy = ImmutablePolicy.builder() //
669             .id(id) //
670             .json(jsonString()) //
671             .ownerServiceId(service) //
672             .ric(rics.getRic(ric)) //
673             .type(addPolicyType(typeName, ric)) //
674             .lastModified(Instant.now()) //
675             .isTransient(false) //
676             .build();
677         policies.put(policy);
678         return policy;
679     }
680
681     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
682         return addPolicy(id, typeName, service, "ric");
683     }
684
685     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
686         return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
687     }
688
689     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
690         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
691
692         String json = gson.toJson(service);
693         return json;
694     }
695
696     private void putService(String name) {
697         putService(name, 0, null);
698     }
699
700     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
701         String url = "/service";
702         String body = createServiceJson(name, keepAliveIntervalSeconds);
703         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
704         if (expectedStatus != null) {
705             assertEquals(expectedStatus, resp.getStatusCode(), "");
706         }
707     }
708
709     private String baseUrl() {
710         return "https://localhost:" + port;
711     }
712
713     private String jsonString() {
714         return "{\"servingCellNrcgi\":\"1\"}";
715     }
716
717     private AsyncRestClient restClient(boolean useTrustValidation) {
718         WebClientConfig config = this.applicationConfig.getWebClientConfig();
719         config = ImmutableWebClientConfig.builder() //
720             .keyStoreType(config.keyStoreType()) //
721             .keyStorePassword(config.keyStorePassword()) //
722             .keyStore(config.keyStore()) //
723             .keyPassword(config.keyPassword()) //
724             .isTrustStoreUsed(useTrustValidation) //
725             .trustStore(config.trustStore()) //
726             .trustStorePassword(config.trustStorePassword()) //
727             .build();
728
729         return new AsyncRestClient(baseUrl(), config);
730     }
731
732     private AsyncRestClient restClient() {
733         return restClient(false);
734     }
735
736     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
737         testErrorCode(request, expStatus, "");
738     }
739
740     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
741         StepVerifier.create(request) //
742             .expectSubscription() //
743             .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
744             .verify();
745     }
746
747     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains) {
748         assertTrue(throwable instanceof WebClientResponseException);
749         WebClientResponseException responseException = (WebClientResponseException) throwable;
750         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
751         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
752         return true;
753     }
754
755     private MockA1Client getA1Client(String ricName) throws ServiceException {
756         return a1ClientFactory.getOrCreateA1Client(ricName);
757     }
758
759     private PolicyType createPolicyType(String policyTypeName) {
760         return ImmutablePolicyType.builder() //
761             .id(policyTypeName) //
762             .schema("{\"title\":\"" + policyTypeName + "\"}") //
763             .build();
764     }
765
766     private PolicyType addPolicyType(String policyTypeName, String ricName) {
767         PolicyType type = createPolicyType(policyTypeName);
768         policyTypes.put(type);
769         addRic(ricName).addSupportedPolicyType(type);
770         return type;
771     }
772
773     private Ric addRic(String ricName) {
774         return addRic(ricName, null);
775     }
776
777     private Ric addRic(String ricName, String managedElement) {
778         if (rics.get(ricName) != null) {
779             return rics.get(ricName);
780         }
781         List<String> mes = new ArrayList<>();
782         if (managedElement != null) {
783             mes.add(managedElement);
784         }
785         RicConfig conf = ImmutableRicConfig.builder() //
786             .ricId(ricName) //
787             .baseUrl(ricName) //
788             .managedElementIds(mes) //
789             .controllerName("") //
790             .build();
791         Ric ric = new Ric(conf);
792         ric.setState(Ric.RicState.AVAILABLE);
793         this.rics.put(ric);
794         return ric;
795     }
796
797     private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
798         List<T> result = new ArrayList<>();
799         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
800         for (JsonElement jsonElement : jsonArr) {
801             T json = gson.fromJson(jsonElement.toString(), clazz);
802             result.add(json);
803         }
804         return result;
805     }
806
807     private static List<String> parseSchemas(String jsonString) {
808         JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
809         List<String> result = new ArrayList<>();
810         for (JsonElement schemaObject : arrayOfSchema) {
811             result.add(schemaObject.toString());
812         }
813         return result;
814     }
815 }