Remove deprecated DMAAP dependency
[policy/drools-applications.git] / controlloop / common / rules-test / src / test / java / org / onap / policy / controlloop / common / rules / test / BaseTestTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP
4  * ================================================================================
5  * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
6  * Modifications Copyright (C) 2021, 2023-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.controlloop.common.rules.test;
23
24 import static org.junit.jupiter.api.Assertions.assertEquals;
25 import static org.junit.jupiter.api.Assertions.assertSame;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27 import static org.mockito.ArgumentMatchers.any;
28 import static org.mockito.ArgumentMatchers.eq;
29 import static org.mockito.Mockito.mock;
30 import static org.mockito.Mockito.spy;
31 import static org.mockito.Mockito.times;
32 import static org.mockito.Mockito.verify;
33 import static org.mockito.Mockito.when;
34
35 import java.util.LinkedList;
36 import java.util.Map;
37 import java.util.Queue;
38 import java.util.concurrent.atomic.AtomicLong;
39 import java.util.function.Predicate;
40 import java.util.function.Supplier;
41 import org.junit.jupiter.api.AfterAll;
42 import org.junit.jupiter.api.BeforeAll;
43 import org.junit.jupiter.api.BeforeEach;
44 import org.junit.jupiter.api.Disabled;
45 import org.junit.jupiter.api.Test;
46 import org.onap.policy.appc.CommonHeader;
47 import org.onap.policy.appc.Request;
48 import org.onap.policy.appclcm.AppcLcmBody;
49 import org.onap.policy.appclcm.AppcLcmCommonHeader;
50 import org.onap.policy.appclcm.AppcLcmInput;
51 import org.onap.policy.appclcm.AppcLcmMessageWrapper;
52 import org.onap.policy.common.utils.coder.StandardCoder;
53 import org.onap.policy.common.utils.coder.StandardCoderInstantAsMillis;
54 import org.onap.policy.controlloop.ControlLoopNotificationType;
55 import org.onap.policy.controlloop.VirtualControlLoopNotification;
56 import org.onap.policy.drools.controller.DroolsController;
57 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
58 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
59 import org.onap.policy.sdnr.PciBody;
60 import org.onap.policy.sdnr.PciCommonHeader;
61 import org.onap.policy.sdnr.PciMessage;
62 import org.onap.policy.sdnr.PciRequest;
63 import org.springframework.test.util.ReflectionTestUtils;
64
65 class BaseTestTest {
66     private static final String POLICY_NAME = "my-policy-name";
67
68     // saved values
69     private static Supplier<HttpClients> httpClientMaker;
70     private static Supplier<Simulators> simMaker;
71     private static Supplier<Topics> topicMaker;
72
73     private BaseTest base;
74     private LinkedList<VirtualControlLoopNotification> clMgtQueue;
75     private Queue<AppcLcmMessageWrapper> appcLcmQueue;
76     private Queue<Request> appcLegacyQueue;
77     private Queue<PciMessage> sdnrQueue;
78     private int permitCount;
79     private int finalCount;
80
81     private final HttpClients httpClients = mock(HttpClients.class);
82     private final Simulators simulators = mock(Simulators.class);
83     private final Topics topics = mock(Topics.class);
84     private final Listener<VirtualControlLoopNotification> policyClMgt = mock();
85     private final Listener<Request> appcClSink = mock();
86     private final Listener<AppcLcmMessageWrapper> appcLcmRead = mock();
87     private final Listener<PciMessage> sdnrClSink = mock();
88     private final DroolsController drools = mock(DroolsController.class);
89     private final ToscaPolicy policy = mock(ToscaPolicy.class);
90     private final ToscaConceptIdentifier policyIdent = mock(ToscaConceptIdentifier.class);
91
92     /**
93      * Saves static values from the class.
94      */
95     @SuppressWarnings("unchecked")
96     @BeforeAll
97     public static void setUpBeforeClass() {
98         httpClientMaker = (Supplier<HttpClients>) ReflectionTestUtils.getField(BaseTest.class, "httpClientMaker");
99         simMaker = (Supplier<Simulators>) ReflectionTestUtils.getField(BaseTest.class, "simMaker");
100         topicMaker = (Supplier<Topics>) ReflectionTestUtils.getField(BaseTest.class, "topicMaker");
101     }
102
103     /**
104      * Restores static values.
105      */
106     @AfterAll
107     public static void tearDownAfterClass() {
108         ReflectionTestUtils.setField(BaseTest.class, "httpClientMaker", httpClientMaker);
109         ReflectionTestUtils.setField(BaseTest.class, "simMaker", simMaker);
110         ReflectionTestUtils.setField(BaseTest.class, "topicMaker", topicMaker);
111     }
112
113     /**
114      * Sets up.
115      */
116     @BeforeEach
117     public void setUp() {
118         when(topics.createListener(eq(BaseTest.POLICY_CL_MGT_TOPIC), eq(VirtualControlLoopNotification.class),
119                         any(StandardCoder.class))).thenReturn(policyClMgt);
120         when(topics.createListener(eq(BaseTest.APPC_LCM_READ_TOPIC), eq(AppcLcmMessageWrapper.class),
121                         any(StandardCoder.class))).thenReturn(appcLcmRead);
122         when(topics.createListener(eq(BaseTest.APPC_CL_TOPIC), eq(Request.class),
123                         any(StandardCoderInstantAsMillis.class))).thenReturn(appcClSink);
124         when(topics.createListener(eq(BaseTest.SDNR_CL_TOPIC), eq(PciMessage.class), any(StandardCoder.class)))
125                         .thenReturn(sdnrClSink);
126
127         Supplier<HttpClients> httpClientMaker = this::makeHttpClients;
128         Supplier<Simulators> simMaker = this::makeSim;
129         Supplier<Topics> topicMaker = this::makeTopics;
130
131         ReflectionTestUtils.setField(BaseTest.class, "httpClientMaker", httpClientMaker);
132         ReflectionTestUtils.setField(BaseTest.class, "simMaker", simMaker);
133         ReflectionTestUtils.setField(BaseTest.class, "topicMaker", topicMaker);
134
135         clMgtQueue = new LinkedList<>();
136         appcLcmQueue = new LinkedList<>();
137         appcLegacyQueue = new LinkedList<>();
138         sdnrQueue = new LinkedList<>();
139
140         when(policyClMgt.await(any())).thenAnswer(args -> {
141             VirtualControlLoopNotification notif = clMgtQueue.remove();
142             Predicate<VirtualControlLoopNotification> pred = args.getArgument(0);
143             assertTrue(pred.test(notif));
144             return notif;
145         });
146
147         when(appcLcmRead.await(any())).thenAnswer(args -> {
148             AppcLcmMessageWrapper req = appcLcmQueue.remove();
149             Predicate<AppcLcmMessageWrapper> pred = args.getArgument(0);
150             assertTrue(pred.test(req));
151             return req;
152         });
153
154         when(appcClSink.await(any())).thenAnswer(args -> {
155             Request req = appcLegacyQueue.remove();
156             Predicate<Request> pred = args.getArgument(0);
157             assertTrue(pred.test(req));
158             return req;
159         });
160
161         when(sdnrClSink.await(any())).thenAnswer(args -> {
162             PciMessage pcireq = sdnrQueue.remove();
163             Predicate<PciMessage> pred = args.getArgument(0);
164             assertTrue(pred.test(pcireq));
165             return pcireq;
166         });
167
168         permitCount = 0;
169         finalCount = 0;
170
171         base = new MyTest();
172
173         BaseTest.initStatics();
174         base.init();
175     }
176
177     @Test
178     void testInitStatics() {
179         assertSame(httpClients, BaseTest.httpClients);
180         assertSame(simulators, BaseTest.simulators);
181     }
182
183     @Test
184     void testFinishStatics() {
185         BaseTest.finishStatics();
186         verify(httpClients).destroy();
187         verify(simulators).destroy();
188     }
189
190     @Test
191     void testInit() {
192         assertSame(topics, BaseTest.getTopics());
193     }
194
195     @Test
196     void testFinish() {
197         base.finish();
198         verify(topics).destroy();
199     }
200
201     @Test
202     void testTestService123Compliant() {
203         enqueueAppcLcm("restart", "restart", "restart", "restart", "rebuild", "migrate");
204         enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
205         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
206
207         base.testService123Compliant();
208
209         assertEquals(1, permitCount);
210         assertEquals(1, finalCount);
211
212         assertTrue(appcLcmQueue.isEmpty());
213         assertTrue(clMgtQueue.isEmpty());
214
215         // initial event
216         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
217
218         // replies to each APPC request
219         verify(topics, times(6)).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
220     }
221
222     @Test
223     void testTestDuplicatesEvents() {
224         // the test expects the count to be incremented by 2 between calls
225         var count = new AtomicLong(5);
226         base = spy(base);
227         when(base.getCreateCount()).thenAnswer(args -> count.getAndAdd(2));
228
229         enqueueAppcLcm("restart", "restart");
230         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
231         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
232
233         clMgtQueue.get(0).setAai(Map.of("generic-vnf.vnf-id", "duplicate-VNF"));
234         clMgtQueue.get(1).setAai(Map.of("generic-vnf.vnf-id", "vCPE_Infrastructure_vGMUX_demo_app"));
235
236         base.testDuplicatesEvents();
237
238         assertEquals(0, permitCount);
239         assertEquals(2, finalCount);
240
241         assertTrue(appcLcmQueue.isEmpty());
242         assertTrue(clMgtQueue.isEmpty());
243
244         // initial events
245         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
246         verify(topics, times(2)).inject(eq(BaseTest.DCAE_TOPIC), any(), any());
247
248         // two restarts
249         verify(topics, times(2)).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
250     }
251
252     @Test
253     void testTestVcpeSunnyDayCompliant() {
254         checkAppcLcmPolicy("restart", base::testVcpeSunnyDayCompliant);
255     }
256
257     @Test
258     void testTestVcpeOnsetFloodPrevention() {
259         enqueueAppcLcm("restart");
260         enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
261         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
262
263         base.testVcpeOnsetFloodPrevention();
264
265         assertEquals(1, permitCount);
266         assertEquals(1, finalCount);
267
268         assertTrue(appcLcmQueue.isEmpty());
269         assertTrue(clMgtQueue.isEmpty());
270
271         // initial events
272         verify(topics, times(3)).inject(eq(BaseTest.DCAE_TOPIC), any());
273
274         // one restart
275         verify(topics).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
276     }
277
278     @Test
279     void testTestVdnsSunnyDayCompliant() {
280         checkHttpPolicy(base::testVdnsSunnyDayCompliant);
281     }
282
283     @Test
284     void testTestVdnsRainyDayCompliant() {
285         checkHttpPolicyCompliantFailure(base::testVdnsRainyDayCompliant);
286     }
287
288     @Test
289     void testTestVfwSunnyDayCompliant() {
290         checkAppcLegacyPolicy("ModifyConfig", base::testVfwSunnyDayCompliant);
291     }
292
293     @Test
294     void testTestVfwRainyDayOverallTimeout() {
295         checkAppcLegacyPolicyFinalFailure("ModifyConfig", base::testVfwRainyDayOverallTimeout);
296     }
297
298     @Test
299     void testTestVfwRainyDayCompliantTimeout() {
300         checkAppcLegacyPolicyFinalFailure("ModifyConfig", base::testVfwRainyDayCompliantTimeout);
301     }
302
303     @Test
304     void testTestVpciSunnyDayCompliant() {
305         checkSdnrPolicy("ModifyConfig", base::testVpciSunnyDayCompliant);
306     }
307
308     @Test
309     void testTestVsonhSunnyDayCompliant() {
310         checkSdnrPolicy("ModifyConfigANR", base::testVsonhSunnyDayCompliant);
311     }
312
313     protected void checkAppcLcmPolicy(String operation, Runnable test) {
314         enqueueAppcLcm(operation);
315         enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
316         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
317
318         test.run();
319
320         assertEquals(1, permitCount);
321         assertEquals(1, finalCount);
322
323         assertTrue(appcLcmQueue.isEmpty());
324         assertTrue(clMgtQueue.isEmpty());
325
326         // initial event
327         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
328
329         // reply to each APPC request
330         verify(topics).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
331     }
332
333     protected void checkAppcLegacyPolicy(String operation, Runnable test) {
334         enqueueAppcLegacy(operation);
335         enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
336         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
337
338         test.run();
339
340         assertEquals(1, permitCount);
341         assertEquals(1, finalCount);
342
343         assertTrue(appcLcmQueue.isEmpty());
344         assertTrue(clMgtQueue.isEmpty());
345
346         // initial event
347         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
348
349         // reply to each APPC request
350         verify(topics).inject(eq(BaseTest.APPC_CL_TOPIC), any(), any());
351     }
352
353     protected void checkAppcLegacyPolicyOperationFailure(String operation, Runnable test) {
354         enqueueAppcLegacy(operation);
355         enqueueClMgt(ControlLoopNotificationType.OPERATION_FAILURE);
356         enqueueClMgt(ControlLoopNotificationType.FINAL_FAILURE);
357
358         test.run();
359
360         assertEquals(1, permitCount);
361         assertEquals(1, finalCount);
362
363         assertTrue(appcLcmQueue.isEmpty());
364         assertTrue(clMgtQueue.isEmpty());
365
366         // initial event
367         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
368
369         // reply to each APPC request
370         verify(topics).inject(eq(BaseTest.APPC_CL_TOPIC), any(), any());
371     }
372
373     protected void checkAppcLegacyPolicyFinalFailure(String operation, Runnable test) {
374         enqueueAppcLegacy(operation);
375         enqueueClMgt(ControlLoopNotificationType.FINAL_FAILURE);
376
377         test.run();
378
379         assertEquals(1, permitCount);
380         assertEquals(1, finalCount);
381
382         assertTrue(appcLcmQueue.isEmpty());
383         assertTrue(clMgtQueue.isEmpty());
384
385         // initial event
386         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
387
388         // There were no requests sent
389     }
390
391     protected void checkSdnrPolicy(String operation, Runnable test) {
392         enqueueSdnr(operation);
393         enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
394         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
395
396         test.run();
397
398         assertEquals(1, permitCount);
399         assertEquals(1, finalCount);
400
401         assertTrue(sdnrQueue.isEmpty());
402         assertTrue(clMgtQueue.isEmpty());
403
404         // initial event
405         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
406
407         // reply to each SDNR request
408         verify(topics).inject(eq(BaseTest.SDNR_CL_RSP_TOPIC), any(), any());
409     }
410
411     protected void checkHttpPolicy(Runnable test) {
412         enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
413         enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
414
415         test.run();
416
417         assertEquals(1, permitCount);
418         assertEquals(1, finalCount);
419
420         assertTrue(clMgtQueue.isEmpty());
421
422         // initial event
423         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
424     }
425
426     protected void checkHttpPolicyCompliantFailure(Runnable test) {
427         enqueueClMgt(ControlLoopNotificationType.OPERATION_FAILURE);
428         enqueueClMgt(ControlLoopNotificationType.FINAL_FAILURE);
429
430         test.run();
431
432         assertEquals(1, permitCount);
433         assertEquals(1, finalCount);
434
435         assertTrue(clMgtQueue.isEmpty());
436
437         // initial event
438         verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
439     }
440
441     private void enqueueClMgt(ControlLoopNotificationType type) {
442         var notif = new VirtualControlLoopNotification();
443         notif.setNotification(type);
444         notif.setPolicyName(POLICY_NAME + ".EVENT.MANAGER.FINAL");
445
446         clMgtQueue.add(notif);
447     }
448
449     private void enqueueAppcLcm(String... operationNames) {
450         for (var oper : operationNames) {
451             var req = new AppcLcmMessageWrapper();
452             req.setRpcName(oper);
453
454             var body = new AppcLcmBody();
455             req.setBody(body);
456
457             var input = new AppcLcmInput();
458             body.setInput(input);
459
460             var header = new AppcLcmCommonHeader();
461             input.setCommonHeader(header);
462
463             header.setSubRequestId("my-subrequest-id");
464
465             appcLcmQueue.add(req);
466         }
467     }
468
469     private void enqueueAppcLegacy(String... operationNames) {
470         for (var oper : operationNames) {
471             var req = new Request();
472             req.setAction(oper);
473
474             var header = new CommonHeader();
475             req.setCommonHeader(header);
476
477             header.setSubRequestId("my-subrequest-id");
478
479             appcLegacyQueue.add(req);
480         }
481     }
482
483     private void enqueueSdnr(String... operationNames) {
484         for (String oper : operationNames) {
485             var pcimessage = new PciMessage();
486             var req = new PciRequest();
487             var body = new PciBody();
488             body.setInput(req);
489             pcimessage.setBody(body);
490             pcimessage.getBody().getInput().setAction(oper);
491             var header = new PciCommonHeader();
492             pcimessage.getBody().getInput().setCommonHeader(header);
493
494             header.setSubRequestId("my-subrequest-id");
495
496             sdnrQueue.add(pcimessage);
497         }
498     }
499
500     private HttpClients makeHttpClients() {
501         return httpClients;
502     }
503
504     private Simulators makeSim() {
505         return simulators;
506     }
507
508     private Topics makeTopics() {
509         return topics;
510     }
511
512     /*
513      * We don't want junit trying to run this, so it's marked "Ignore".
514      */
515     @Disabled
516     private class MyTest extends BaseTest {
517
518         @Override
519         protected void waitForLockAndPermit(ToscaPolicy policy, Listener<VirtualControlLoopNotification> policyClMgt) {
520             permitCount++;
521         }
522
523         @Override
524         protected VirtualControlLoopNotification waitForFinal(ToscaPolicy policy,
525                         Listener<VirtualControlLoopNotification> policyClMgt, ControlLoopNotificationType finalType) {
526             finalCount++;
527             return policyClMgt.await(notif -> notif.getNotification() == finalType);
528         }
529     }
530 }