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