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