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