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