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