Merge "Add https support in A1 controller"
[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         if (policyTypeName.isEmpty()) {
279             return "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName;
280         } else {
281             return "/policy?id=" + policyInstanceId + "&ric=" + ricName + "&service=" + serviceName + "&type="
282                 + policyTypeName;
283         }
284     }
285
286     @Test
287     public void testPutPolicy() throws Exception {
288         String serviceName = "service1";
289         String ricName = "ric1";
290         String policyTypeName = "type1";
291         String policyInstanceId = "instance1";
292
293         putService(serviceName);
294         addPolicyType(policyTypeName, ricName);
295
296         String url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
297         final String policyBody = jsonString();
298         this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
299
300         restClient().put(url, policyBody).block();
301
302         Policy policy = policies.getPolicy(policyInstanceId);
303         assertThat(policy).isNotNull();
304         assertThat(policy.id()).isEqualTo(policyInstanceId);
305         assertThat(policy.ownerServiceName()).isEqualTo(serviceName);
306         assertThat(policy.ric().name()).isEqualTo("ric1");
307
308         url = "/policies";
309         String rsp = restClient().get(url).block();
310         assertThat(rsp.contains(policyInstanceId)).isTrue();
311
312         url = "/policy?id=" + policyInstanceId;
313         rsp = restClient().get(url).block();
314         assertThat(rsp).isEqualTo(policyBody);
315
316         // Test of error codes
317         url = putPolicyUrl(serviceName, ricName + "XX", policyTypeName, policyInstanceId);
318         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
319
320         url = putPolicyUrl(serviceName, ricName, policyTypeName + "XX", policyInstanceId);
321         testErrorCode(restClient().put(url, policyBody), HttpStatus.NOT_FOUND);
322
323         url = putPolicyUrl(serviceName, ricName, policyTypeName, policyInstanceId);
324         this.rics.getRic(ricName).setState(Ric.RicState.SYNCHRONIZING);
325         testErrorCode(restClient().put(url, policyBody), HttpStatus.LOCKED);
326         this.rics.getRic(ricName).setState(Ric.RicState.AVAILABLE);
327     }
328
329     @Test
330     /**
331      * Test that HttpStatus and body from failing REST call to A1 is passed on to
332      * the caller.
333      *
334      * @throws ServiceException
335      */
336     public void testErrorFromRIC() throws ServiceException {
337         putService("service1");
338         addPolicyType("type1", "ric1");
339
340         String url = putPolicyUrl("service1", "ric1", "type1", "id1");
341         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
342         HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
343         String responseBody = "Refused";
344         byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
345
346         WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
347             responseBodyBytes, StandardCharsets.UTF_8, null);
348         doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
349
350         // PUT Policy
351         testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
352
353         // DELETE POLICY
354         this.addPolicy("instance1", "type1", "service1", "ric1");
355         doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
356         testErrorCode(restClient().delete("/policy?id=instance1"), httpStatus, responseBody);
357
358         // GET STATUS
359         this.addPolicy("instance1", "type1", "service1", "ric1");
360         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
361         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus, responseBody);
362
363         // Check that empty response body is OK
364         a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
365         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
366         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus);
367     }
368
369     @Test
370     public void testPutTypelessPolicy() throws Exception {
371         putService("service1");
372         addPolicyType("", "ric1");
373         String url = putPolicyUrl("service1", "ric1", "", "id1");
374         restClient().put(url, jsonString()).block();
375
376         String rsp = restClient().get("/policies").block();
377         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
378         assertThat(info).size().isEqualTo(1);
379         PolicyInfo policyInfo = info.get(0);
380         assertThat(policyInfo.id.equals("id1")).isTrue();
381         assertThat(policyInfo.type.equals("")).isTrue();
382     }
383
384     @Test
385     public void testRefuseToUpdatePolicy() throws Exception {
386         // Test that only the json can be changed for a already created policy
387         // In this case service is attempted to be changed
388         this.addRic("ric1");
389         this.addRic("ricXXX");
390         this.addPolicy("instance1", "type1", "service1", "ric1");
391         this.addPolicy("instance2", "type1", "service1", "ricXXX");
392
393         // Try change ric1 -> ricXXX
394         String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
395         testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
396     }
397
398     @Test
399     public void testGetPolicy() throws Exception {
400         String url = "/policy?id=id";
401         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
402         {
403             String rsp = restClient().get(url).block();
404             assertThat(rsp).isEqualTo(policy.json());
405         }
406         {
407             policies.remove(policy);
408             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
409         }
410     }
411
412     @Test
413     public void testDeletePolicy() throws Exception {
414         addPolicy("id", "typeName", "service1", "ric1");
415         assertThat(policies.size()).isEqualTo(1);
416
417         String url = "/policy?id=id";
418         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
419
420         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
421         assertThat(policies.size()).isEqualTo(0);
422
423         // Delete a non existing policy
424         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
425     }
426
427     @Test
428     public void testGetPolicySchemas() throws Exception {
429         addPolicyType("type1", "ric1");
430         addPolicyType("type2", "ric2");
431
432         String url = "/policy_schemas";
433         String rsp = this.restClient().get(url).block();
434         assertThat(rsp).contains("type1");
435         assertThat(rsp).contains("[{\"title\":\"type2\"}");
436
437         List<String> info = parseSchemas(rsp);
438         assertThat(info.size()).isEqualTo(2);
439
440         url = "/policy_schemas?ric=ric1";
441         rsp = restClient().get(url).block();
442         assertThat(rsp).contains("type1");
443         info = parseSchemas(rsp);
444         assertThat(info.size()).isEqualTo(1);
445
446         // Get schema for non existing RIC
447         url = "/policy_schemas?ric=ric1XXX";
448         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
449     }
450
451     @Test
452     public void testGetPolicySchema() throws Exception {
453         addPolicyType("type1", "ric1");
454         addPolicyType("type2", "ric2");
455
456         String url = "/policy_schema?id=type1";
457         String rsp = restClient().get(url).block();
458         logger.info(rsp);
459         assertThat(rsp).contains("type1");
460         assertThat(rsp).contains("title");
461
462         // Get non existing schema
463         url = "/policy_schema?id=type1XX";
464         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
465     }
466
467     @Test
468     public void testGetPolicyTypes() throws Exception {
469         addPolicyType("type1", "ric1");
470         addPolicyType("type2", "ric2");
471
472         String url = "/policy_types";
473         String rsp = restClient().get(url).block();
474         assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
475
476         url = "/policy_types?ric=ric1";
477         rsp = restClient().get(url).block();
478         assertThat(rsp).isEqualTo("[\"type1\"]");
479
480         // Get policy types for non existing RIC
481         url = "/policy_types?ric=ric1XXX";
482         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
483     }
484
485     @Test
486     public void testGetPolicies() throws Exception {
487         addPolicy("id1", "type1", "service1");
488
489         String url = "/policies";
490         String rsp = restClient().get(url).block();
491         logger.info(rsp);
492         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
493         assertThat(info).size().isEqualTo(1);
494         PolicyInfo policyInfo = info.get(0);
495         assert (policyInfo.validate());
496         assertThat(policyInfo.id).isEqualTo("id1");
497         assertThat(policyInfo.type).isEqualTo("type1");
498         assertThat(policyInfo.service).isEqualTo("service1");
499     }
500
501     @Test
502     public void testGetPoliciesFilter() throws Exception {
503         addPolicy("id1", "type1", "service1");
504         addPolicy("id2", "type1", "service2");
505         addPolicy("id3", "type2", "service1");
506
507         String url = "/policies?type=type1";
508         String rsp = restClient().get(url).block();
509         logger.info(rsp);
510         assertThat(rsp).contains("id1");
511         assertThat(rsp).contains("id2");
512         assertThat(rsp.contains("id3")).isFalse();
513
514         url = "/policies?type=type1&service=service2";
515         rsp = restClient().get(url).block();
516         logger.info(rsp);
517         assertThat(rsp.contains("id1")).isFalse();
518         assertThat(rsp).contains("id2");
519         assertThat(rsp.contains("id3")).isFalse();
520
521         // Test get policies for non existing type
522         url = "/policies?type=type1XXX";
523         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
524
525         // Test get policies for non existing RIC
526         url = "/policies?ric=XXX";
527         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
528     }
529
530     @Test
531     public void testGetPolicyIdsFilter() throws Exception {
532         addPolicy("id1", "type1", "service1", "ric1");
533         addPolicy("id2", "type1", "service2", "ric1");
534         addPolicy("id3", "type2", "service1", "ric1");
535
536         String url = "/policy_ids?type=type1";
537         String rsp = restClient().get(url).block();
538         logger.info(rsp);
539         assertThat(rsp).contains("id1");
540         assertThat(rsp).contains("id2");
541         assertThat(rsp.contains("id3")).isFalse();
542
543         url = "/policy_ids?type=type1&service=service1&ric=ric1";
544         rsp = restClient().get(url).block();
545         assertThat(rsp).isEqualTo("[\"id1\"]");
546
547         // Test get policy ids for non existing type
548         url = "/policy_ids?type=type1XXX";
549         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
550
551         // Test get policy ids for non existing RIC
552         url = "/policy_ids?ric=XXX";
553         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
554     }
555
556     @Test
557     public void testPutAndGetService() throws Exception {
558         // PUT
559         putService("name", 0, HttpStatus.CREATED);
560         putService("name", 0, HttpStatus.OK);
561
562         // GET one service
563         String url = "/services?name=name";
564         String rsp = restClient().get(url).block();
565         List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
566         assertThat(info.size()).isEqualTo(1);
567         ServiceStatus status = info.iterator().next();
568         assertThat(status.keepAliveIntervalSeconds).isEqualTo(0);
569         assertThat(status.serviceName).isEqualTo("name");
570
571         // GET (all)
572         url = "/services";
573         rsp = restClient().get(url).block();
574         assertThat(rsp.contains("name")).isTrue();
575         logger.info(rsp);
576
577         // Keep alive
578         url = "/services/keepalive?name=name";
579         ResponseEntity<String> entity = restClient().putForEntity(url).block();
580         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
581
582         // DELETE service
583         assertThat(services.size()).isEqualTo(1);
584         url = "/services?name=name";
585         restClient().delete(url).block();
586         assertThat(services.size()).isEqualTo(0);
587
588         // Keep alive, no registerred service
589         testErrorCode(restClient().put("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
590
591         // PUT servive with bad payload
592         testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
593         testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
594         testErrorCode(restClient().put("/service", createServiceJson("name", -123)), HttpStatus.BAD_REQUEST);
595         testErrorCode(restClient().put("/service", createServiceJson("name", 0, "missing.portandprotocol.com")),
596             HttpStatus.BAD_REQUEST);
597
598         // GET non existing servive
599         testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
600     }
601
602     @Test
603     public void testServiceSupervision() throws Exception {
604         putService("service1", 1, HttpStatus.CREATED);
605         addPolicyType("type1", "ric1");
606
607         String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
608         final String policyBody = jsonString();
609         restClient().put(url, policyBody).block();
610
611         assertThat(policies.size()).isEqualTo(1);
612         assertThat(services.size()).isEqualTo(1);
613
614         // Timeout after ~1 second
615         await().untilAsserted(() -> assertThat(policies.size()).isEqualTo(0));
616         assertThat(services.size()).isEqualTo(0);
617     }
618
619     @Test
620     public void testGetPolicyStatus() throws Exception {
621         addPolicy("id", "typeName", "service1", "ric1");
622         assertThat(policies.size()).isEqualTo(1);
623
624         String url = "/policy_status?id=id";
625         String rsp = restClient().get(url).block();
626         assertThat(rsp.equals("OK")).isTrue();
627
628         // GET non existing policy status
629         url = "/policy_status?id=XXX";
630         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
631     }
632
633     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
634         addRic(ric);
635         Policy p = ImmutablePolicy.builder().id(id) //
636             .json(jsonString()) //
637             .ownerServiceName(service) //
638             .ric(rics.getRic(ric)) //
639             .type(addPolicyType(typeName, ric)) //
640             .lastModified("lastModified").build();
641         policies.put(p);
642         return p;
643     }
644
645     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
646         return addPolicy(id, typeName, service, "ric");
647     }
648
649     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
650         return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
651     }
652
653     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
654         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
655
656         String json = gson.toJson(service);
657         return json;
658     }
659
660     private void putService(String name) {
661         putService(name, 0, null);
662     }
663
664     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
665         String url = "/service";
666         String body = createServiceJson(name, keepAliveIntervalSeconds);
667         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
668         if (expectedStatus != null) {
669             assertEquals(expectedStatus, resp.getStatusCode(), "");
670         }
671     }
672
673     private String baseUrl() {
674         return "https://localhost:" + port;
675     }
676
677     private String jsonString() {
678         return "{\"servingCellNrcgi\":\"1\"}";
679     }
680
681     @Test
682     public void testConcurrency() throws Exception {
683         final Instant startTime = Instant.now();
684         List<Thread> threads = new ArrayList<>();
685         a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
686         addRic("ric");
687         addPolicyType("type1", "ric");
688         addPolicyType("type2", "ric");
689
690         for (int i = 0; i < 100; ++i) {
691             Thread t =
692                 new Thread(new ConcurrencyTestRunnable(baseUrl(), supervision, a1ClientFactory, rics, policyTypes),
693                     "TestThread_" + i);
694             t.start();
695             threads.add(t);
696         }
697         for (Thread t : threads) {
698             t.join();
699         }
700         assertThat(policies.size()).isEqualTo(0);
701         logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
702     }
703
704     private AsyncRestClient restClient() {
705         return new AsyncRestClient(baseUrl());
706     }
707
708     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
709         testErrorCode(request, expStatus, "");
710     }
711
712     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
713         StepVerifier.create(request) //
714             .expectSubscription() //
715             .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
716             .verify();
717     }
718
719     private boolean checkWebClientError(Throwable t, HttpStatus expStatus, String responseContains) {
720         assertTrue(t instanceof WebClientResponseException);
721         WebClientResponseException e = (WebClientResponseException) t;
722         assertThat(e.getStatusCode()).isEqualTo(expStatus);
723         assertThat(e.getResponseBodyAsString()).contains(responseContains);
724         return true;
725     }
726
727     private MockA1Client getA1Client(String ricName) throws ServiceException {
728         return a1ClientFactory.getOrCreateA1Client(ricName);
729     }
730
731     private PolicyType createPolicyType(String policyTypeName) {
732         return ImmutablePolicyType.builder() //
733             .name(policyTypeName) //
734             .schema("{\"title\":\"" + policyTypeName + "\"}") //
735             .build();
736     }
737
738     private PolicyType addPolicyType(String policyTypeName, String ricName) {
739         PolicyType type = createPolicyType(policyTypeName);
740         policyTypes.put(type);
741         addRic(ricName).addSupportedPolicyType(type);
742         return type;
743     }
744
745     private Ric addRic(String ricName) {
746         return addRic(ricName, null);
747     }
748
749     private Ric addRic(String ricName, String managedElement) {
750         if (rics.get(ricName) != null) {
751             return rics.get(ricName);
752         }
753         List<String> mes = new ArrayList<>();
754         if (managedElement != null) {
755             mes.add(managedElement);
756         }
757         RicConfig conf = ImmutableRicConfig.builder() //
758             .name(ricName) //
759             .baseUrl(ricName) //
760             .managedElementIds(mes) //
761             .controllerName("") //
762             .build();
763         Ric ric = new Ric(conf);
764         ric.setState(Ric.RicState.AVAILABLE);
765         this.rics.put(ric);
766         return ric;
767     }
768
769     private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
770         List<T> result = new ArrayList<>();
771         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
772         for (JsonElement jsonElement : jsonArr) {
773             T o = gson.fromJson(jsonElement.toString(), clazz);
774             result.add(o);
775         }
776         return result;
777     }
778
779     private static List<String> parseSchemas(String jsonString) {
780         JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
781         List<String> result = new ArrayList<>();
782         for (JsonElement schemaObject : arrayOfSchema) {
783             result.add(schemaObject.toString());
784         }
785         return result;
786     }
787 }