f42a631f81bba16dd08974293e118d4520f665d1
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / MockPolicyAgent.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.awaitility.Awaitility.await;
24
25 import com.google.gson.JsonObject;
26 import com.google.gson.JsonParser;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.net.URL;
31 import java.nio.file.Files;
32
33 import org.junit.jupiter.api.Test;
34 import org.junit.jupiter.api.extension.ExtendWith;
35 import org.oransc.policyagent.configuration.ApplicationConfig;
36 import org.oransc.policyagent.repository.ImmutablePolicy;
37 import org.oransc.policyagent.repository.ImmutablePolicyType;
38 import org.oransc.policyagent.repository.Policies;
39 import org.oransc.policyagent.repository.Policy;
40 import org.oransc.policyagent.repository.PolicyType;
41 import org.oransc.policyagent.repository.PolicyTypes;
42 import org.oransc.policyagent.repository.Ric;
43 import org.oransc.policyagent.repository.Rics;
44 import org.oransc.policyagent.utils.MockA1ClientFactory;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.boot.test.context.SpringBootTest;
49 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
50 import org.springframework.boot.test.context.TestConfiguration;
51 import org.springframework.boot.web.server.LocalServerPort;
52 import org.springframework.context.annotation.Bean;
53 import org.springframework.test.context.TestPropertySource;
54 import org.springframework.test.context.junit.jupiter.SpringExtension;
55 import org.springframework.util.StringUtils;
56
57 @ExtendWith(SpringExtension.class)
58 @SpringBootTest(webEnvironment = WebEnvironment.DEFINED_PORT)
59 @TestPropertySource(
60     properties = { //
61         "server.ssl.key-store=./config/keystore.jks", //
62         "app.webclient.trust-store=./config/truststore.jks"})
63 class MockPolicyAgent {
64     private static final Logger logger = LoggerFactory.getLogger(MockPolicyAgent.class);
65
66     @Autowired
67     Rics rics;
68
69     @Autowired
70     Policies policies;
71
72     @Autowired
73     PolicyTypes policyTypes;
74
75     @Autowired
76     ApplicationConfig applicationConfig;
77
78     static class MockApplicationConfig extends ApplicationConfig {
79         @Override
80         public String getLocalConfigurationFilePath() {
81             URL url = MockApplicationConfig.class.getClassLoader().getResource("test_application_configuration.json");
82             return url.getFile();
83         }
84     }
85
86     /**
87      * Overrides the BeanFactory.
88      */
89     @TestConfiguration
90     static class TestBeanFactory {
91
92         private final Rics rics = new Rics();
93         private final Policies policies = new Policies();
94         private final PolicyTypes policyTypes = new PolicyTypes();
95
96         @Bean
97         public ApplicationConfig getApplicationConfig() {
98             return new MockApplicationConfig();
99         }
100
101         @Bean
102         public MockA1ClientFactory getA1ClientFactory() {
103             PolicyTypes ricTypes = new PolicyTypes();
104             loadTypes(ricTypes);
105             return new MockA1ClientFactory(ricTypes);
106         }
107
108         @Bean
109         public Policies getPolicies() {
110             return this.policies;
111         }
112
113         @Bean
114         public PolicyTypes getPolicyTypes() {
115             return this.policyTypes;
116         }
117
118         @Bean
119         public Rics getRics() {
120             return this.rics;
121         }
122
123         private static File[] getResourceFolderFiles(String folder) {
124             return getFile(folder).listFiles();
125         }
126
127         private static String readFile(File file) throws IOException {
128             return new String(Files.readAllBytes(file.toPath()));
129         }
130
131         private void loadTypes(PolicyTypes policyTypes) {
132             File[] files = getResourceFolderFiles("policy_types/");
133             for (File file : files) {
134                 try {
135                     String schema = readFile(file);
136                     String typeName = title(schema);
137                     PolicyType type = ImmutablePolicyType.builder().name(typeName).schema(schema).build();
138                     policyTypes.put(type);
139                 } catch (Exception e) {
140                     logger.error("Could not load json schema ", e);
141                 }
142             }
143             policyTypes.put(ImmutablePolicyType.builder().name("").schema("{}").build());
144         }
145     }
146
147     private static File getFile(String path) {
148         ClassLoader loader = Thread.currentThread().getContextClassLoader();
149         URL url = loader.getResource(path);
150         return new File(url.getPath());
151     }
152
153     @LocalServerPort
154     private int port;
155
156     private void keepServerAlive() throws InterruptedException, IOException {
157         waitForConfigurationToBeLoaded();
158         loadInstances();
159         logger.info("Keeping server alive!");
160         synchronized (this) {
161             this.wait();
162         }
163     }
164
165     private void waitForConfigurationToBeLoaded() throws IOException {
166         String json = getConfigJsonFromFile();
167         try {
168             int noOfRicsInConfigFile = StringUtils.countOccurrencesOf(json, "baseUrl");
169             await().until(() -> rics.size() == noOfRicsInConfigFile);
170         } catch (Exception e) {
171             logger.info("Loaded rics: {}, and no of rics in config file: {} never matched!", rics.size(),
172                 StringUtils.countOccurrencesOf(json, "baseUrl"));
173         }
174     }
175
176     private static String title(String jsonSchema) {
177         JsonObject parsedSchema = (JsonObject) JsonParser.parseString(jsonSchema);
178         String title = parsedSchema.get("title").getAsString();
179         return title;
180     }
181
182     private void loadInstances() throws IOException {
183         PolicyType unnamedPolicyType = policyTypes.get("");
184         Ric ric = rics.get("ric1");
185         String json = getConfigJsonFromFile();
186
187         Policy policy = ImmutablePolicy.builder() //
188             .id("typelessPolicy") //
189             .json(json) //
190             .ownerServiceName("MockPolicyAgent") //
191             .ric(ric) //
192             .type(unnamedPolicyType) //
193             .lastModified("now") //
194             .isTransient(false) //
195             .build();
196         this.policies.put(policy);
197     }
198
199     private String getConfigJsonFromFile() throws IOException {
200         File jsonFile = getFile("test_application_configuration.json");
201         String json = new String(Files.readAllBytes(jsonFile.toPath()));
202         return json;
203     }
204
205     @Test
206     @SuppressWarnings("squid:S2699") // Tests should include assertions. This test is only for keeping the server
207                                      // alive, so it will only be confusing to add an assertion.
208     void runMock() throws Exception {
209         keepServerAlive();
210     }
211
212 }