4de5c71ffcf9151ca81183033abdaf93ee89b68e
[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
363      * the caller.
364      *
365      * @throws ServiceException
366      */
367     void testErrorFromRic() throws ServiceException {
368         putService("service1");
369         addPolicyType("type1", "ric1");
370
371         String url = putPolicyUrl("service1", "ric1", "type1", "id1");
372         MockA1Client a1Client = a1ClientFactory.getOrCreateA1Client("ric1");
373         HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
374         String responseBody = "Refused";
375         byte[] responseBodyBytes = responseBody.getBytes(StandardCharsets.UTF_8);
376
377         WebClientResponseException a1Exception = new WebClientResponseException(httpStatus.value(), "statusText", null,
378             responseBodyBytes, StandardCharsets.UTF_8, null);
379         doReturn(Mono.error(a1Exception)).when(a1Client).putPolicy(any());
380
381         // PUT Policy
382         testErrorCode(restClient().put(url, "{}"), httpStatus, responseBody);
383
384         // DELETE POLICY
385         this.addPolicy("instance1", "type1", "service1", "ric1");
386         doReturn(Mono.error(a1Exception)).when(a1Client).deletePolicy(any());
387         testErrorCode(restClient().delete("/policy?id=instance1"), httpStatus, responseBody);
388
389         // GET STATUS
390         this.addPolicy("instance1", "type1", "service1", "ric1");
391         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
392         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus, responseBody);
393
394         // Check that empty response body is OK
395         a1Exception = new WebClientResponseException(httpStatus.value(), "", null, null, null, null);
396         doReturn(Mono.error(a1Exception)).when(a1Client).getPolicyStatus(any());
397         testErrorCode(restClient().get("/policy_status?id=instance1"), httpStatus);
398     }
399
400     @Test
401     void testPutTypelessPolicy() throws Exception {
402         putService("service1");
403         addPolicyType("", "ric1");
404         String url = putPolicyUrl("service1", "ric1", "", "id1");
405         restClient().put(url, jsonString()).block();
406
407         String rsp = restClient().get("/policies").block();
408         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
409         assertThat(info).hasSize(1);
410         PolicyInfo policyInfo = info.get(0);
411         assertThat(policyInfo.id).isEqualTo("id1");
412         assertThat(policyInfo.type).isEmpty();
413     }
414
415     @Test
416     void testRefuseToUpdatePolicy() throws Exception {
417         // Test that only the json can be changed for a already created policy
418         // In this case service is attempted to be changed
419         this.addRic("ric1");
420         this.addRic("ricXXX");
421         this.addPolicy("instance1", "type1", "service1", "ric1");
422         this.addPolicy("instance2", "type1", "service1", "ricXXX");
423
424         // Try change ric1 -> ricXXX
425         String urlWrongRic = putPolicyUrl("service1", "ricXXX", "type1", "instance1");
426         testErrorCode(restClient().put(urlWrongRic, jsonString()), HttpStatus.CONFLICT);
427     }
428
429     @Test
430     void testGetPolicy() throws Exception {
431         String url = "/policy?id=id";
432         Policy policy = addPolicy("id", "typeName", "service1", "ric1");
433         {
434             String rsp = restClient().get(url).block();
435             assertThat(rsp).isEqualTo(policy.json());
436         }
437         {
438             policies.remove(policy);
439             testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
440         }
441     }
442
443     @Test
444     void testDeletePolicy() throws Exception {
445         addPolicy("id", "typeName", "service1", "ric1");
446         assertThat(policies.size()).isEqualTo(1);
447
448         String url = "/policy?id=id";
449         ResponseEntity<String> entity = restClient().deleteForEntity(url).block();
450
451         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT);
452         assertThat(policies.size()).isZero();
453
454         // Delete a non existing policy
455         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
456     }
457
458     @Test
459     void testGetPolicySchemas() throws Exception {
460         addPolicyType("type1", "ric1");
461         addPolicyType("type2", "ric2");
462
463         String url = "/policy_schemas";
464         String rsp = this.restClient().get(url).block();
465         assertThat(rsp).contains("type1") //
466             .contains("[{\"title\":\"type2\"}");
467
468         List<String> info = parseSchemas(rsp);
469         assertThat(info).hasSize(2);
470
471         url = "/policy_schemas?ric=ric1";
472         rsp = restClient().get(url).block();
473         assertThat(rsp).contains("type1");
474         info = parseSchemas(rsp);
475         assertThat(info).hasSize(1);
476
477         // Get schema for non existing RIC
478         url = "/policy_schemas?ric=ric1XXX";
479         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
480     }
481
482     @Test
483     void testGetPolicySchema() throws Exception {
484         addPolicyType("type1", "ric1");
485         addPolicyType("type2", "ric2");
486
487         String url = "/policy_schema?id=type1";
488         String rsp = restClient().get(url).block();
489         logger.info(rsp);
490         assertThat(rsp).contains("type1") //
491             .contains("title");
492
493         // Get non existing schema
494         url = "/policy_schema?id=type1XX";
495         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
496     }
497
498     @Test
499     void testGetPolicyTypes() throws Exception {
500         addPolicyType("type1", "ric1");
501         addPolicyType("type2", "ric2");
502
503         String url = "/policy_types";
504         String rsp = restClient().get(url).block();
505         assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
506
507         url = "/policy_types?ric=ric1";
508         rsp = restClient().get(url).block();
509         assertThat(rsp).isEqualTo("[\"type1\"]");
510
511         // Get policy types for non existing RIC
512         url = "/policy_types?ric=ric1XXX";
513         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
514     }
515
516     @Test
517     void testGetPolicies() throws Exception {
518         addPolicy("id1", "type1", "service1");
519
520         String url = "/policies";
521         String rsp = restClient().get(url).block();
522         logger.info(rsp);
523         List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
524         assertThat(info).hasSize(1);
525         PolicyInfo policyInfo = info.get(0);
526         assert (policyInfo.validate());
527         assertThat(policyInfo.id).isEqualTo("id1");
528         assertThat(policyInfo.type).isEqualTo("type1");
529         assertThat(policyInfo.service).isEqualTo("service1");
530     }
531
532     @Test
533     void testGetPoliciesFilter() throws Exception {
534         addPolicy("id1", "type1", "service1");
535         addPolicy("id2", "type1", "service2");
536         addPolicy("id3", "type2", "service1");
537
538         String url = "/policies?type=type1";
539         String rsp = restClient().get(url).block();
540         logger.info(rsp);
541         assertThat(rsp).contains("id1") //
542             .contains("id2") //
543             .doesNotContain("id3");
544
545         url = "/policies?type=type1&service=service2";
546         rsp = restClient().get(url).block();
547         logger.info(rsp);
548         assertThat(rsp).doesNotContain("id1") //
549             .contains("id2") //
550             .doesNotContain("id3");
551
552         // Test get policies for non existing type
553         url = "/policies?type=type1XXX";
554         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
555
556         // Test get policies for non existing RIC
557         url = "/policies?ric=XXX";
558         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
559     }
560
561     @Test
562     void testGetPolicyIdsFilter() throws Exception {
563         addPolicy("id1", "type1", "service1", "ric1");
564         addPolicy("id2", "type1", "service2", "ric1");
565         addPolicy("id3", "type2", "service1", "ric1");
566
567         String url = "/policy_ids?type=type1";
568         String rsp = restClient().get(url).block();
569         logger.info(rsp);
570         assertThat(rsp).contains("id1") //
571             .contains("id2") //
572             .doesNotContain("id3");
573
574         url = "/policy_ids?type=type1&service=service1&ric=ric1";
575         rsp = restClient().get(url).block();
576         assertThat(rsp).isEqualTo("[\"id1\"]");
577
578         // Test get policy ids for non existing type
579         url = "/policy_ids?type=type1XXX";
580         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
581
582         // Test get policy ids for non existing RIC
583         url = "/policy_ids?ric=XXX";
584         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
585     }
586
587     @Test
588     void testPutAndGetService() throws Exception {
589         // PUT
590         String serviceName = "name";
591         putService(serviceName, 0, HttpStatus.CREATED);
592         putService(serviceName, 0, HttpStatus.OK);
593
594         // GET one service
595         String url = "/services?name=name";
596         String rsp = restClient().get(url).block();
597         List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
598         assertThat(info).hasSize(1);
599         ServiceStatus status = info.iterator().next();
600         assertThat(status.keepAliveIntervalSeconds).isZero();
601         assertThat(status.serviceName).isEqualTo(serviceName);
602
603         // GET (all)
604         url = "/services";
605         rsp = restClient().get(url).block();
606         assertThat(rsp).as("Response contains service name").contains(serviceName);
607         logger.info(rsp);
608
609         // Keep alive
610         url = "/services/keepalive?name=name";
611         ResponseEntity<String> entity = restClient().putForEntity(url).block();
612         assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
613
614         // DELETE service
615         assertThat(services.size()).isEqualTo(1);
616         url = "/services?name=name";
617         restClient().delete(url).block();
618         assertThat(services.size()).isZero();
619
620         // Keep alive, no registered service
621         testErrorCode(restClient().put("/services/keepalive?name=name", ""), HttpStatus.NOT_FOUND);
622
623         // PUT servive with bad payload
624         testErrorCode(restClient().put("/service", "crap"), HttpStatus.BAD_REQUEST);
625         testErrorCode(restClient().put("/service", "{}"), HttpStatus.BAD_REQUEST);
626         testErrorCode(restClient().put("/service", createServiceJson(serviceName, -123)), HttpStatus.BAD_REQUEST);
627         testErrorCode(restClient().put("/service", createServiceJson(serviceName, 0, "missing.portandprotocol.com")),
628             HttpStatus.BAD_REQUEST);
629
630         // GET non existing service
631         testErrorCode(restClient().get("/services?name=XXX"), HttpStatus.NOT_FOUND);
632     }
633
634     @Test
635     void testServiceSupervision() throws Exception {
636         putService("service1", 1, HttpStatus.CREATED);
637         addPolicyType("type1", "ric1");
638
639         String url = putPolicyUrl("service1", "ric1", "type1", "instance1");
640         final String policyBody = jsonString();
641         restClient().put(url, policyBody).block();
642
643         assertThat(policies.size()).isEqualTo(1);
644         assertThat(services.size()).isEqualTo(1);
645
646         // Timeout after ~1 second
647         await().untilAsserted(() -> assertThat(policies.size()).isZero());
648         assertThat(services.size()).isZero();
649     }
650
651     @Test
652     void testGetPolicyStatus() throws Exception {
653         addPolicy("id", "typeName", "service1", "ric1");
654         assertThat(policies.size()).isEqualTo(1);
655
656         String url = "/policy_status?id=id";
657         String rsp = restClient().get(url).block();
658         assertThat(rsp).isEqualTo("OK");
659
660         // GET non existing policy status
661         url = "/policy_status?id=XXX";
662         testErrorCode(restClient().get(url), HttpStatus.NOT_FOUND);
663     }
664
665     private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
666         addRic(ric);
667         Policy policy = ImmutablePolicy.builder() //
668             .id(id) //
669             .json(jsonString()) //
670             .ownerServiceName(service) //
671             .ric(rics.getRic(ric)) //
672             .type(addPolicyType(typeName, ric)) //
673             .lastModified("lastModified") //
674             .isTransient(false) //
675             .build();
676         policies.put(policy);
677         return policy;
678     }
679
680     private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
681         return addPolicy(id, typeName, service, "ric");
682     }
683
684     private String createServiceJson(String name, long keepAliveIntervalSeconds) {
685         return createServiceJson(name, keepAliveIntervalSeconds, "https://examples.javacodegeeks.com/core-java/");
686     }
687
688     private String createServiceJson(String name, long keepAliveIntervalSeconds, String url) {
689         ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, keepAliveIntervalSeconds, url);
690
691         String json = gson.toJson(service);
692         return json;
693     }
694
695     private void putService(String name) {
696         putService(name, 0, null);
697     }
698
699     private void putService(String name, long keepAliveIntervalSeconds, @Nullable HttpStatus expectedStatus) {
700         String url = "/service";
701         String body = createServiceJson(name, keepAliveIntervalSeconds);
702         ResponseEntity<String> resp = restClient().putForEntity(url, body).block();
703         if (expectedStatus != null) {
704             assertEquals(expectedStatus, resp.getStatusCode(), "");
705         }
706     }
707
708     private String baseUrl() {
709         return "https://localhost:" + port;
710     }
711
712     private String jsonString() {
713         return "{\"servingCellNrcgi\":\"1\"}";
714     }
715
716     @Test
717     void testConcurrency() throws Exception {
718         final Instant startTime = Instant.now();
719         List<Thread> threads = new ArrayList<>();
720         a1ClientFactory.setResponseDelay(Duration.ofMillis(1));
721         addRic("ric");
722         addPolicyType("type1", "ric");
723         addPolicyType("type2", "ric");
724         List<ConcurrencyTestRunnable> tests = new ArrayList<>();
725
726         for (int i = 0; i < 10; ++i) {
727             ConcurrencyTestRunnable test =
728                 new ConcurrencyTestRunnable(restClient(), supervision, a1ClientFactory, rics, policyTypes);
729             Thread thread = new Thread(test, "TestThread_" + i);
730             thread.start();
731             threads.add(thread);
732             tests.add(test);
733         }
734         for (Thread t : threads) {
735             t.join();
736         }
737         for (ConcurrencyTestRunnable test : tests) {
738             assertThat(test.isFailed()).isFalse();
739         }
740
741         assertThat(policies.size()).isZero();
742         logger.info("Concurrency test took " + Duration.between(startTime, Instant.now()));
743     }
744
745     private AsyncRestClient restClient(boolean useTrustValidation) {
746         WebClientConfig config = this.applicationConfig.getWebClientConfig();
747         config = ImmutableWebClientConfig.builder() //
748             .keyStoreType(config.keyStoreType()) //
749             .keyStorePassword(config.keyStorePassword()) //
750             .keyStore(config.keyStore()) //
751             .keyPassword(config.keyPassword()) //
752             .isTrustStoreUsed(useTrustValidation) //
753             .trustStore(config.trustStore()) //
754             .trustStorePassword(config.trustStorePassword()) //
755             .build();
756
757         return new AsyncRestClient(baseUrl(), config);
758     }
759
760     private AsyncRestClient restClient() {
761         return restClient(false);
762     }
763
764     private void testErrorCode(Mono<?> request, HttpStatus expStatus) {
765         testErrorCode(request, expStatus, "");
766     }
767
768     private void testErrorCode(Mono<?> request, HttpStatus expStatus, String responseContains) {
769         StepVerifier.create(request) //
770             .expectSubscription() //
771             .expectErrorMatches(t -> checkWebClientError(t, expStatus, responseContains)) //
772             .verify();
773     }
774
775     private boolean checkWebClientError(Throwable throwable, HttpStatus expStatus, String responseContains) {
776         assertTrue(throwable instanceof WebClientResponseException);
777         WebClientResponseException responseException = (WebClientResponseException) throwable;
778         assertThat(responseException.getStatusCode()).isEqualTo(expStatus);
779         assertThat(responseException.getResponseBodyAsString()).contains(responseContains);
780         return true;
781     }
782
783     private MockA1Client getA1Client(String ricName) throws ServiceException {
784         return a1ClientFactory.getOrCreateA1Client(ricName);
785     }
786
787     private PolicyType createPolicyType(String policyTypeName) {
788         return ImmutablePolicyType.builder() //
789             .name(policyTypeName) //
790             .schema("{\"title\":\"" + policyTypeName + "\"}") //
791             .build();
792     }
793
794     private PolicyType addPolicyType(String policyTypeName, String ricName) {
795         PolicyType type = createPolicyType(policyTypeName);
796         policyTypes.put(type);
797         addRic(ricName).addSupportedPolicyType(type);
798         return type;
799     }
800
801     private Ric addRic(String ricName) {
802         return addRic(ricName, null);
803     }
804
805     private Ric addRic(String ricName, String managedElement) {
806         if (rics.get(ricName) != null) {
807             return rics.get(ricName);
808         }
809         List<String> mes = new ArrayList<>();
810         if (managedElement != null) {
811             mes.add(managedElement);
812         }
813         RicConfig conf = ImmutableRicConfig.builder() //
814             .name(ricName) //
815             .baseUrl(ricName) //
816             .managedElementIds(mes) //
817             .controllerName("") //
818             .build();
819         Ric ric = new Ric(conf);
820         ric.setState(Ric.RicState.AVAILABLE);
821         this.rics.put(ric);
822         return ric;
823     }
824
825     private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
826         List<T> result = new ArrayList<>();
827         JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
828         for (JsonElement jsonElement : jsonArr) {
829             T json = gson.fromJson(jsonElement.toString(), clazz);
830             result.add(json);
831         }
832         return result;
833     }
834
835     private static List<String> parseSchemas(String jsonString) {
836         JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
837         List<String> result = new ArrayList<>();
838         for (JsonElement schemaObject : arrayOfSchema) {
839             result.add(schemaObject.toString());
840         }
841         return result;
842     }
843 }