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