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