2 * ========================LICENSE_START=================================
5 * Copyright (C) 2019 Nordix Foundation
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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===================================
21 package org.oransc.policyagent;
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertFalse;
28 import com.google.gson.Gson;
29 import com.google.gson.GsonBuilder;
30 import com.google.gson.JsonArray;
31 import com.google.gson.JsonElement;
32 import com.google.gson.JsonParser;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.List;
37 import java.util.Vector;
39 import org.junit.jupiter.api.Test;
40 import org.junit.jupiter.api.extension.ExtendWith;
41 import org.oransc.policyagent.configuration.ApplicationConfig;
42 import org.oransc.policyagent.configuration.ImmutableRicConfig;
43 import org.oransc.policyagent.configuration.RicConfig;
44 import org.oransc.policyagent.controllers.PolicyInfo;
45 import org.oransc.policyagent.controllers.ServiceRegistrationInfo;
46 import org.oransc.policyagent.controllers.ServiceStatus;
47 import org.oransc.policyagent.exceptions.ServiceException;
48 import org.oransc.policyagent.repository.ImmutablePolicy;
49 import org.oransc.policyagent.repository.ImmutablePolicyType;
50 import org.oransc.policyagent.repository.Policies;
51 import org.oransc.policyagent.repository.Policy;
52 import org.oransc.policyagent.repository.PolicyType;
53 import org.oransc.policyagent.repository.PolicyTypes;
54 import org.oransc.policyagent.repository.Ric;
55 import org.oransc.policyagent.repository.Ric.RicState;
56 import org.oransc.policyagent.repository.Rics;
57 import org.oransc.policyagent.repository.Services;
58 import org.oransc.policyagent.tasks.RepositorySupervision;
59 import org.oransc.policyagent.utils.MockA1Client;
60 import org.oransc.policyagent.utils.MockA1ClientFactory;
61 import org.springframework.beans.factory.annotation.Autowired;
62 import org.springframework.boot.test.context.SpringBootTest;
63 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
64 import org.springframework.boot.test.context.TestConfiguration;
65 import org.springframework.boot.web.server.LocalServerPort;
66 import org.springframework.context.ApplicationContext;
67 import org.springframework.context.annotation.Bean;
68 import org.springframework.http.HttpEntity;
69 import org.springframework.http.HttpHeaders;
70 import org.springframework.http.HttpStatus;
71 import org.springframework.http.HttpStatus.Series;
72 import org.springframework.http.MediaType;
73 import org.springframework.http.ResponseEntity;
74 import org.springframework.http.client.ClientHttpResponse;
75 import org.springframework.test.context.junit.jupiter.SpringExtension;
76 import org.springframework.web.client.ResponseErrorHandler;
77 import org.springframework.web.client.RestTemplate;
79 @ExtendWith(SpringExtension.class)
80 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
81 public class ApplicationTest {
83 ApplicationContext context;
89 private Policies policies;
92 private PolicyTypes policyTypes;
95 MockA1ClientFactory a1ClientFactory;
98 RepositorySupervision supervision;
103 private static Gson gson = new GsonBuilder() //
107 public static class MockApplicationConfig extends ApplicationConfig {
109 public String getLocalConfigurationFilePath() {
110 return ""; // No config file loaded for the test
115 * Overrides the BeanFactory.
118 static class TestBeanFactory {
119 private final PolicyTypes policyTypes = new PolicyTypes();
122 public ApplicationConfig getApplicationConfig() {
123 return new MockApplicationConfig();
127 MockA1ClientFactory getA1ClientFactory() {
128 return new MockA1ClientFactory(this.policyTypes);
132 public Policies getPolicies() {
133 return new Policies();
137 public PolicyTypes getPolicyTypes() {
138 return this.policyTypes;
142 public Rics getRics() {
150 private final RestTemplate restTemplate = new RestTemplate();
152 public class RestTemplateResponseErrorHandler implements ResponseErrorHandler {
155 public boolean hasError(ClientHttpResponse httpResponse) throws IOException {
156 return (httpResponse.getStatusCode().series() == Series.CLIENT_ERROR
157 || httpResponse.getStatusCode().series() == Series.SERVER_ERROR);
161 public void handleError(ClientHttpResponse httpResponse) throws IOException {
162 System.out.println("Error " + httpResponse.toString());
166 private void reset() {
170 assertThat(policies.size()).isEqualTo(0);
171 restTemplate.setErrorHandler(new RestTemplateResponseErrorHandler());
175 public void testGetRics() throws Exception {
178 String url = baseUrl() + "/rics";
179 String rsp = this.restTemplate.getForObject(url, String.class);
180 System.out.println(rsp);
181 assertThat(rsp).contains("kista_1");
183 url = baseUrl() + "/rics?policyType=STD_PolicyModelUnconstrained_0.2.0";
184 rsp = this.restTemplate.getForObject(url, String.class);
185 assertThat(rsp).isEqualTo("[]");
189 public void testRecovery() throws Exception {
191 Policy policy2 = addPolicy("policyId2", "typeName", "service", "ric");
193 getA1Client("ric").putPolicy(policy2); // put it in the RIC
194 policies.remove(policy2); // Remove it from the repo -> should be deleted in the RIC
196 Policy policy = addPolicy("policyId", "typeName", "service", "ric"); // This should be created in the RIC
197 supervision.checkAllRics(); // The created policy should be put in the RIC
198 await().untilAsserted(() -> RicState.RECOVERING.equals(rics.getRic("ric").getState()));
199 await().untilAsserted(() -> RicState.IDLE.equals(rics.getRic("ric").getState()));
201 Policies ricPolicies = getA1Client("ric").getPolicies();
202 assertThat(ricPolicies.size()).isEqualTo(1);
203 Policy ricPolicy = ricPolicies.get("policyId");
204 assertThat(ricPolicy.json()).isEqualTo(policy.json());
207 MockA1Client getA1Client(String ricName) throws ServiceException {
208 return a1ClientFactory.getOrCreateA1Client(ricName);
212 public void testGetRic() throws Exception {
214 Ric ric = addRic("ric1");
215 ric.addManagedElement("kista_1");
216 String url = baseUrl() + "/ric?managedElementId=kista_1";
218 String rsp = this.restTemplate.getForObject(url, String.class);
219 System.out.println(rsp);
220 assertThat(rsp).isEqualTo("ric1");
224 public void testPutPolicy() throws Exception {
226 putService("service1");
227 addPolicyType("type1", "ric1");
229 String url = baseUrl() + "/policy?type=type1&instance=instance1&ric=ric1&service=service1";
230 final String json = jsonString();
231 this.rics.getRic("ric1").setState(Ric.RicState.IDLE);
233 this.restTemplate.put(url, createJsonHttpEntity(json));
234 Policy policy = policies.getPolicy("instance1");
236 assertThat(policy).isNotNull();
237 assertThat(policy.id()).isEqualTo("instance1");
238 assertThat(policy.ownerServiceName()).isEqualTo("service1");
240 url = baseUrl() + "/policies";
241 String rsp = this.restTemplate.getForObject(url, String.class);
242 System.out.println(rsp);
245 private PolicyType addPolicyType(String policyTypeName, String ricName) {
246 PolicyType type = ImmutablePolicyType.builder() //
247 .name(policyTypeName) //
248 .schema("{\"title\":\"" + policyTypeName + "\"}") //
251 policyTypes.put(type);
252 addRic(ricName).addSupportedPolicyType(type);
256 private Ric addRic(String ricName) {
257 if (rics.get(ricName) != null) {
258 return rics.get(ricName);
260 Vector<String> mes = new Vector<>();
261 RicConfig conf = ImmutableRicConfig.builder() //
264 .managedElementIds(mes) //
266 Ric ric = new Ric(conf);
271 private String createServiceJson(String name) {
272 ServiceRegistrationInfo service = new ServiceRegistrationInfo(name, 1, "callbackUrl");
274 String json = gson.toJson(service);
278 HttpEntity<String> createJsonHttpEntity(String content) {
279 HttpHeaders headers = new HttpHeaders();
280 headers.setContentType(MediaType.APPLICATION_JSON);
281 return new HttpEntity<String>(content, headers);
284 private void putService(String name) {
285 String url = baseUrl() + "/service";
286 HttpEntity<String> entity = createJsonHttpEntity(createServiceJson(name));
287 this.restTemplate.put(url, entity);
290 private String jsonString() {
291 return "{\n \"servingCellNrcgi\": \"1\"\n }";
294 private Policy addPolicy(String id, String typeName, String service, String ric) throws ServiceException {
296 Policy p = ImmutablePolicy.builder().id(id) //
297 .json(jsonString()) //
298 .ownerServiceName(service) //
299 .ric(rics.getRic(ric)) //
300 .type(addPolicyType(typeName, ric)) //
301 .lastModified("lastModified").build();
306 private Policy addPolicy(String id, String typeName, String service) throws ServiceException {
307 return addPolicy(id, typeName, service, "ric");
310 private String baseUrl() {
311 return "http://localhost:" + port;
315 public void testGetPolicy() throws Exception {
316 String url = baseUrl() + "/policy?instance=id";
317 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
319 String rsp = this.restTemplate.getForObject(url, String.class);
320 assertThat(rsp).isEqualTo(policy.json());
323 policies.remove(policy);
324 ResponseEntity<String> rsp = this.restTemplate.getForEntity(url, String.class);
325 assertThat(rsp.getStatusCodeValue()).isEqualTo(HttpStatus.NO_CONTENT.value());
330 public void testDeletePolicy() throws Exception {
332 String url = baseUrl() + "/policy?instance=id";
333 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
334 policy.ric().setState(Ric.RicState.IDLE);
335 assertThat(policies.size()).isEqualTo(1);
337 this.restTemplate.delete(url);
339 assertThat(policies.size()).isEqualTo(0);
343 public void testGetPolicySchemas() throws Exception {
345 addPolicyType("type1", "ric1");
346 addPolicyType("type2", "ric2");
348 String url = baseUrl() + "/policy_schemas";
349 String rsp = this.restTemplate.getForObject(url, String.class);
350 System.out.println("*** " + rsp);
351 assertThat(rsp).contains("type1");
352 assertThat(rsp).contains("type2");
353 assertThat(rsp).contains("title");
355 List<String> info = parseSchemas(rsp);
356 assertEquals(2, info.size());
358 url = baseUrl() + "/policy_schemas?ric=ric1";
359 rsp = this.restTemplate.getForObject(url, String.class);
360 assertThat(rsp).contains("type1");
361 info = parseSchemas(rsp);
362 assertEquals(1, info.size());
366 public void testGetPolicySchema() throws Exception {
368 addPolicyType("type1", "ric1");
369 addPolicyType("type2", "ric2");
371 String url = baseUrl() + "/policy_schema?id=type1";
372 String rsp = this.restTemplate.getForObject(url, String.class);
373 System.out.println(rsp);
374 assertThat(rsp).contains("type1");
375 assertThat(rsp).contains("title");
379 public void testGetPolicyTypes() throws Exception {
381 addPolicyType("type1", "ric1");
382 addPolicyType("type2", "ric2");
384 String url = baseUrl() + "/policy_types";
385 String rsp = this.restTemplate.getForObject(url, String.class);
386 assertThat(rsp).isEqualTo("[\"type2\",\"type1\"]");
388 url = baseUrl() + "/policy_types?ric=ric1";
389 rsp = this.restTemplate.getForObject(url, String.class);
390 assertThat(rsp).isEqualTo("[\"type1\"]");
394 public void testGetPolicies() throws Exception {
395 String url = baseUrl() + "/policies";
396 addPolicy("id1", "type1", "service1");
398 String rsp = this.restTemplate.getForObject(url, String.class);
399 System.out.println(rsp);
400 List<PolicyInfo> info = parseList(rsp, PolicyInfo.class);
401 assertThat(info).size().isEqualTo(1);
402 PolicyInfo policyInfo = info.get(0);
403 assert (policyInfo.validate());
404 assertThat(policyInfo.id).isEqualTo("id1");
405 assertThat(policyInfo.type).isEqualTo("type1");
406 assertThat(policyInfo.service).isEqualTo("service1");
410 public void testGetPoliciesFilter() throws Exception {
411 addPolicy("id1", "type1", "service1");
412 addPolicy("id2", "type1", "service2");
413 addPolicy("id3", "type2", "service1");
415 String url = baseUrl() + "/policies?type=type1";
416 String rsp = this.restTemplate.getForObject(url, String.class);
417 System.out.println(rsp);
418 assertThat(rsp).contains("id1");
419 assertThat(rsp).contains("id2");
420 assertFalse(rsp.contains("id3"));
422 url = baseUrl() + "/policies?type=type1&service=service2";
423 rsp = this.restTemplate.getForObject(url, String.class);
424 System.out.println(rsp);
425 assertFalse(rsp.contains("id1"));
426 assertThat(rsp).contains("id2");
427 assertFalse(rsp.contains("id3"));
431 public void testPutAndGetService() throws Exception {
437 String url = baseUrl() + "/services?name=name";
438 String rsp = this.restTemplate.getForObject(url, String.class);
439 List<ServiceStatus> info = parseList(rsp, ServiceStatus.class);
440 assertThat(info.size() == 1);
441 ServiceStatus status = info.iterator().next();
442 assertThat(status.keepAliveIntervalSeconds == 1);
443 assertThat(status.name.equals("name"));
446 url = baseUrl() + "/services";
447 rsp = this.restTemplate.getForObject(url, String.class);
448 assertThat(rsp.contains("name"));
449 System.out.println(rsp);
452 url = baseUrl() + "/services/keepalive?name=name";
453 rsp = this.restTemplate.postForObject(url, null, String.class);
454 assertThat(rsp.contains("OK"));
457 assertThat(services.size() == 1);
458 url = baseUrl() + "/services?name=name";
459 this.restTemplate.delete(url);
460 assertThat(services.size() == 0);
462 // Keep alive, no registerred service
463 url = baseUrl() + "/services/keepalive?name=nameXXX";
464 ResponseEntity<String> entity = this.restTemplate.postForEntity(url, null, String.class);
465 assertThat(entity.getStatusCode().equals(HttpStatus.NOT_FOUND));
469 public void testGetPolicyStatus() throws Exception {
471 Policy policy = addPolicy("id", "typeName", "service1", "ric1");
472 policy.ric().setState(Ric.RicState.IDLE);
473 assertThat(policies.size()).isEqualTo(1);
475 String url = baseUrl() + "/policy_status?instance=id";
476 String rsp = this.restTemplate.getForObject(url, String.class);
477 assertThat(rsp.equals("OK"));
480 private static <T> List<T> parseList(String jsonString, Class<T> clazz) {
481 List<T> result = new ArrayList<>();
482 JsonArray jsonArr = JsonParser.parseString(jsonString).getAsJsonArray();
483 for (JsonElement jsonElement : jsonArr) {
484 T o = gson.fromJson(jsonElement.toString(), clazz);
490 private static List<String> parseSchemas(String jsonString) {
491 JsonArray arrayOfSchema = JsonParser.parseString(jsonString).getAsJsonArray();
492 List<String> result = new ArrayList<>();
493 for (JsonElement schemaObject : arrayOfSchema) {
494 result.add(schemaObject.toString());