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