Removing deprecated DMAAP library
[policy/drools-pdp.git] / policy-management / src / test / java / org / onap / policy / drools / system / PolicyEngineTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2017-2022 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2024 Nordix Foundation.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.drools.system;
23
24 import static org.awaitility.Awaitility.await;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertFalse;
27 import static org.junit.jupiter.api.Assertions.assertTrue;
28
29 import java.io.File;
30 import java.io.IOException;
31 import java.nio.file.Files;
32 import java.nio.file.Path;
33 import java.nio.file.Paths;
34 import java.util.Properties;
35 import java.util.concurrent.TimeUnit;
36 import org.junit.jupiter.api.AfterAll;
37 import org.junit.jupiter.api.BeforeAll;
38 import org.junit.jupiter.api.MethodOrderer;
39 import org.junit.jupiter.api.Test;
40 import org.junit.jupiter.api.TestMethodOrder;
41 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
42 import org.onap.policy.common.endpoints.event.comm.TopicSink;
43 import org.onap.policy.common.endpoints.event.comm.bus.NoopTopicFactories;
44 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
45 import org.onap.policy.common.utils.gson.GsonTestUtils;
46 import org.onap.policy.drools.persistence.SystemPersistenceConstants;
47 import org.onap.policy.drools.properties.DroolsPropertyConstants;
48 import org.onap.policy.drools.protocol.coders.EventProtocolCoderConstants;
49 import org.onap.policy.drools.protocol.coders.EventProtocolParams;
50 import org.onap.policy.drools.protocol.coders.JsonProtocolFilter;
51 import org.onap.policy.drools.protocol.configuration.DroolsConfiguration;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
54
55 /**
56  * PolicyEngine unit tests.
57  */
58
59 @TestMethodOrder(MethodOrderer.DisplayName.class)
60 class PolicyEngineTest {
61     /**
62      * Default Telemetry port for JUnits.
63      */
64     public static final int DEFAULT_TELEMETRY_PORT = 9698;
65
66     /**
67      * Test JUnit Controller Name.
68      */
69     public static final String TEST_CONTROLLER_NAME = "foo";
70
71     /**
72      * Controller Configuration File.
73      */
74     public static final String TEST_CONTROLLER_FILE = TEST_CONTROLLER_NAME + "-controller.properties";
75
76     /**
77      * Controller Configuration Backup File.
78      */
79     public static final String TEST_CONTROLLER_FILE_BAK = TEST_CONTROLLER_FILE + ".bak";
80
81     /**
82      * Coder Group.
83      */
84     private static final String ENCODER_GROUP = "foo";
85
86     /**
87      * Coder Artifact.
88      */
89     private static final String ENCODER_ARTIFACT = "bar";
90
91     /**
92      * Coder Version.
93      */
94     private static final String ENCODER_VERSION = null;
95
96     /**
97      * noop topic.
98      */
99     private static final String NOOP_TOPIC = "JUNIT";
100
101     /**
102      * logger.
103      */
104     private static final Logger logger = LoggerFactory.getLogger(PolicyEngineTest.class);
105
106     private static GsonTestUtils gson;
107
108     /**
109      * clean up working directory.
110      */
111     protected static void cleanUpWorkingDir() {
112         final Path testControllerPath =
113                         Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(),
114                                         TEST_CONTROLLER_FILE);
115         try {
116             Files.deleteIfExists(testControllerPath);
117         } catch (final Exception e) {
118             logger.info("Problem cleaning {}", testControllerPath, e);
119         }
120
121         final Path testControllerBakPath =
122                         Paths.get(SystemPersistenceConstants.getManager().getConfigurationPath().toString(),
123                                         TEST_CONTROLLER_FILE_BAK);
124         try {
125             Files.deleteIfExists(testControllerBakPath);
126         } catch (final Exception e) {
127             logger.info("Problem cleaning {}", testControllerBakPath, e);
128         }
129     }
130
131     /**
132      * Start up.
133      *
134      * @throws IOException throws IO exception
135      */
136     @BeforeAll
137     static void startUp() throws IOException {
138         logger.info("startUp");
139
140         gson = new GsonTestUtils();
141
142         cleanUpWorkingDir();
143
144         /* ensure presence of config directory */
145         final Path configDir = Paths.get(SystemPersistenceConstants.DEFAULT_CONFIGURATION_DIR);
146         if (Files.notExists(configDir)) {
147             Files.createDirectories(configDir);
148         }
149     }
150
151     @Test
152     void test100Configure() {
153         var manager = (PolicyEngineManager) PolicyEngineConstants.getManager();
154         var engineProps = manager.defaultTelemetryConfig();
155
156         /* override default port */
157         engineProps.put(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "."
158                         + PolicyEngineConstants.TELEMETRY_SERVER_DEFAULT_NAME
159                         + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX, "" + DEFAULT_TELEMETRY_PORT);
160
161         assertFalse(manager.isAlive());
162         manager.setHostName("foo");
163         manager.setClusterName("0");
164         manager.configure(engineProps);
165         assertFalse(PolicyEngineConstants.getManager().isAlive());
166
167         logger.info("engine {} has configuration {}", PolicyEngineConstants.getManager(), engineProps);
168
169         PolicyEngineConstants.getManager().getStats().getGroupStat().setBirthTime(0L);
170         gson.compareGson(PolicyEngineConstants.getManager(),
171                         new File(PolicyEngineTest.class.getSimpleName() + "Config.json"));
172     }
173
174     @Test
175     void test200Start() {
176         logger.info("enter");
177
178         PolicyEngineConstants.getManager().start();
179
180         assertTrue(PolicyEngineConstants.getManager().isAlive());
181         assertFalse(PolicyEngineConstants.getManager().isLocked());
182         assertFalse(PolicyEngineConstants.getManager().getHttpServers().isEmpty());
183         assertTrue(PolicyEngineConstants.getManager().getHttpServers().get(0).isAlive());
184     }
185
186     @Test
187     void test300Lock() {
188         logger.info("enter");
189
190         PolicyEngineConstants.getManager().lock();
191
192         assertTrue(PolicyEngineConstants.getManager().isAlive());
193         assertTrue(PolicyEngineConstants.getManager().isLocked());
194         assertFalse(PolicyEngineConstants.getManager().getHttpServers().isEmpty());
195         assertTrue(PolicyEngineConstants.getManager().getHttpServers().get(0).isAlive());
196     }
197
198     @Test
199     void test301Unlock() {
200         logger.info("enter");
201
202         PolicyEngineConstants.getManager().unlock();
203
204         assertTrue(PolicyEngineConstants.getManager().isAlive());
205         assertFalse(PolicyEngineConstants.getManager().isLocked());
206         assertFalse(PolicyEngineConstants.getManager().getHttpServers().isEmpty());
207         assertTrue(PolicyEngineConstants.getManager().getHttpServers().get(0).isAlive());
208     }
209
210     @Test
211     void test350TopicDeliver() {
212         final Properties noopSinkProperties = new Properties();
213         noopSinkProperties.put(PolicyEndPointProperties.PROPERTY_NOOP_SINK_TOPICS, NOOP_TOPIC);
214
215         TopicEndpointManager.getManager().addTopicSinks(noopSinkProperties).get(0).start();
216
217         EventProtocolCoderConstants.getManager().addEncoder(
218                 EventProtocolParams.builder().groupId(ENCODER_GROUP).artifactId(ENCODER_ARTIFACT)
219                         .topic(NOOP_TOPIC).eventClass(DroolsConfiguration.class.getName())
220                         .protocolFilter(new JsonProtocolFilter()).customGsonCoder(null)
221                         .modelClassLoaderHash(DroolsConfiguration.class.getName().hashCode()).build());
222
223         assertTrue(PolicyEngineConstants.getManager().deliver(NOOP_TOPIC,
224                 new DroolsConfiguration(ENCODER_ARTIFACT, ENCODER_GROUP, ENCODER_VERSION)));
225
226         final TopicSink sink = NoopTopicFactories.getSinkFactory().get(NOOP_TOPIC);
227         assertTrue(sink.getRecentEvents()[0].contains(ENCODER_GROUP));
228         assertTrue(sink.getRecentEvents()[0].contains(ENCODER_ARTIFACT));
229
230         EventProtocolCoderConstants.getManager().removeEncoders(ENCODER_GROUP, ENCODER_ARTIFACT, NOOP_TOPIC);
231     }
232
233     @Test
234     void test400ControllerAdd() {
235         logger.info("enter");
236
237         final Properties controllerProperties = new Properties();
238         controllerProperties.put(DroolsPropertyConstants.PROPERTY_CONTROLLER_NAME, TEST_CONTROLLER_NAME);
239         PolicyEngineConstants.getManager().createPolicyController(TEST_CONTROLLER_NAME, controllerProperties);
240
241         assertEquals(1, PolicyControllerConstants.getFactory().inventory().size());
242
243         PolicyEngineConstants.getManager().getStats().getGroupStat().setBirthTime(0L);
244         gson.compareGson(PolicyEngineConstants.getManager(),
245                         new File(PolicyEngineTest.class.getSimpleName() + "Add.json"));
246     }
247
248     @Test
249     void test401ControllerVerify() {
250         logger.info("enter");
251
252         final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME);
253
254         assertFalse(testController.isAlive());
255         assertFalse(testController.isLocked());
256
257         testController.start();
258
259         assertTrue(testController.isAlive());
260         assertFalse(testController.isLocked());
261     }
262
263     @Test
264     void test500Deactivate() {
265         logger.info("enter");
266
267         PolicyEngineConstants.getManager().deactivate();
268
269         final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME);
270         assertFalse(testController.isAlive());
271         assertTrue(testController.isLocked());
272         assertTrue(PolicyEngineConstants.getManager().isLocked());
273         assertTrue(PolicyEngineConstants.getManager().isAlive());
274     }
275
276     @Test
277     void test501Activate() {
278         logger.info("enter");
279
280         PolicyEngineConstants.getManager().activate();
281
282         final PolicyController testController = PolicyControllerConstants.getFactory().get(TEST_CONTROLLER_NAME);
283         assertTrue(testController.isAlive());
284         assertFalse(testController.isLocked());
285         assertFalse(PolicyEngineConstants.getManager().isLocked());
286         assertTrue(PolicyEngineConstants.getManager().isAlive());
287     }
288
289     @Test
290     void test900ControllerRemove() {
291         logger.info("enter");
292
293         PolicyEngineConstants.getManager().removePolicyController(TEST_CONTROLLER_NAME);
294         assertTrue(PolicyControllerConstants.getFactory().inventory().isEmpty());
295     }
296
297     @Test
298     void test901Stop() {
299         logger.info("enter");
300
301         /* Shutdown managed resources */
302         PolicyControllerConstants.getFactory().shutdown();
303         TopicEndpointManager.getManager().shutdown();
304         PolicyEngineConstants.getManager().stop();
305
306         await().atMost(10, TimeUnit.SECONDS).until(() -> !PolicyEngineConstants.getManager().isAlive());
307         assertFalse(PolicyEngineConstants.getManager().isAlive());
308     }
309 }