aboutsummaryrefslogtreecommitdiffstats
path: root/controlloop/common/rules-test/src/test/java/org/onap/policy/controlloop/common/rules/test/BaseTestTest.java
blob: cc2bda03e0e0fdf4bbbf58112693124101276646 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
/*-
 * ============LICENSE_START=======================================================
 * ONAP
 * ================================================================================
 * Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2021,2023 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.controlloop.common.rules.test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.onap.policy.appc.CommonHeader;
import org.onap.policy.appc.Request;
import org.onap.policy.appclcm.AppcLcmBody;
import org.onap.policy.appclcm.AppcLcmCommonHeader;
import org.onap.policy.appclcm.AppcLcmDmaapWrapper;
import org.onap.policy.appclcm.AppcLcmInput;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.common.utils.coder.StandardCoderInstantAsMillis;
import org.onap.policy.controlloop.ControlLoopNotificationType;
import org.onap.policy.controlloop.VirtualControlLoopNotification;
import org.onap.policy.drools.controller.DroolsController;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.onap.policy.sdnr.PciBody;
import org.onap.policy.sdnr.PciCommonHeader;
import org.onap.policy.sdnr.PciMessage;
import org.onap.policy.sdnr.PciRequest;
import org.springframework.test.util.ReflectionTestUtils;

class BaseTestTest {
    private static final String POLICY_NAME = "my-policy-name";

    // saved values
    private static Supplier<HttpClients> httpClientMaker;
    private static Supplier<Simulators> simMaker;
    private static Supplier<Topics> topicMaker;

    private BaseTest base;
    private LinkedList<VirtualControlLoopNotification> clMgtQueue;
    private Queue<AppcLcmDmaapWrapper> appcLcmQueue;
    private Queue<Request> appcLegacyQueue;
    private Queue<PciMessage> sdnrQueue;
    private int permitCount;
    private int finalCount;

    private final HttpClients httpClients = mock(HttpClients.class);
    private final Simulators simulators = mock(Simulators.class);
    private final Topics topics = mock(Topics.class);
    private final Listener<VirtualControlLoopNotification> policyClMgt = mock();
    private final Listener<Request> appcClSink = mock();
    private final Listener<AppcLcmDmaapWrapper> appcLcmRead = mock();
    private final Listener<PciMessage> sdnrClSink = mock();
    private final DroolsController drools = mock(DroolsController.class);
    private final ToscaPolicy policy = mock(ToscaPolicy.class);
    private final ToscaConceptIdentifier policyIdent = mock(ToscaConceptIdentifier.class);

    /**
     * Saves static values from the class.
     */
    @SuppressWarnings("unchecked")
    @BeforeAll
    public static void setUpBeforeClass() {
        httpClientMaker = (Supplier<HttpClients>) ReflectionTestUtils.getField(BaseTest.class, "httpClientMaker");
        simMaker = (Supplier<Simulators>) ReflectionTestUtils.getField(BaseTest.class, "simMaker");
        topicMaker = (Supplier<Topics>) ReflectionTestUtils.getField(BaseTest.class, "topicMaker");
    }

    /**
     * Restores static values.
     */
    @AfterAll
    public static void tearDownAfterClass() {
        ReflectionTestUtils.setField(BaseTest.class, "httpClientMaker", httpClientMaker);
        ReflectionTestUtils.setField(BaseTest.class, "simMaker", simMaker);
        ReflectionTestUtils.setField(BaseTest.class, "topicMaker", topicMaker);
    }

    /**
     * Sets up.
     */
    @BeforeEach
    public void setUp() {
        when(topics.createListener(eq(BaseTest.POLICY_CL_MGT_TOPIC), eq(VirtualControlLoopNotification.class),
                        any(StandardCoder.class))).thenReturn(policyClMgt);
        when(topics.createListener(eq(BaseTest.APPC_LCM_READ_TOPIC), eq(AppcLcmDmaapWrapper.class),
                        any(StandardCoder.class))).thenReturn(appcLcmRead);
        when(topics.createListener(eq(BaseTest.APPC_CL_TOPIC), eq(Request.class),
                        any(StandardCoderInstantAsMillis.class))).thenReturn(appcClSink);
        when(topics.createListener(eq(BaseTest.SDNR_CL_TOPIC), eq(PciMessage.class), any(StandardCoder.class)))
                        .thenReturn(sdnrClSink);

        Supplier<HttpClients> httpClientMaker = this::makeHttpClients;
        Supplier<Simulators> simMaker = this::makeSim;
        Supplier<Topics> topicMaker = this::makeTopics;

        ReflectionTestUtils.setField(BaseTest.class, "httpClientMaker", httpClientMaker);
        ReflectionTestUtils.setField(BaseTest.class, "simMaker", simMaker);
        ReflectionTestUtils.setField(BaseTest.class, "topicMaker", topicMaker);

        clMgtQueue = new LinkedList<>();
        appcLcmQueue = new LinkedList<>();
        appcLegacyQueue = new LinkedList<>();
        sdnrQueue = new LinkedList<>();

        when(policyClMgt.await(any())).thenAnswer(args -> {
            VirtualControlLoopNotification notif = clMgtQueue.remove();
            Predicate<VirtualControlLoopNotification> pred = args.getArgument(0);
            assertTrue(pred.test(notif));
            return notif;
        });

        when(appcLcmRead.await(any())).thenAnswer(args -> {
            AppcLcmDmaapWrapper req = appcLcmQueue.remove();
            Predicate<AppcLcmDmaapWrapper> pred = args.getArgument(0);
            assertTrue(pred.test(req));
            return req;
        });

        when(appcClSink.await(any())).thenAnswer(args -> {
            Request req = appcLegacyQueue.remove();
            Predicate<Request> pred = args.getArgument(0);
            assertTrue(pred.test(req));
            return req;
        });

        when(sdnrClSink.await(any())).thenAnswer(args -> {
            PciMessage pcireq = sdnrQueue.remove();
            Predicate<PciMessage> pred = args.getArgument(0);
            assertTrue(pred.test(pcireq));
            return pcireq;
        });

        permitCount = 0;
        finalCount = 0;

        base = new MyTest();

        BaseTest.initStatics();
        base.init();
    }

    @Test
    void testInitStatics() {
        assertSame(httpClients, BaseTest.httpClients);
        assertSame(simulators, BaseTest.simulators);
    }

    @Test
    void testFinishStatics() {
        BaseTest.finishStatics();
        verify(httpClients).destroy();
        verify(simulators).destroy();
    }

    @Test
    void testInit() {
        assertSame(topics, BaseTest.getTopics());
    }

    @Test
    void testFinish() {
        base.finish();
        verify(topics).destroy();
    }

    @Test
    void testTestService123Compliant() {
        enqueueAppcLcm("restart", "restart", "restart", "restart", "rebuild", "migrate");
        enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        base.testService123Compliant();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());

        // replies to each APPC request
        verify(topics, times(6)).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
    }

    @Test
    void testTestDuplicatesEvents() {
        // the test expects the count to be incremented by 2 between calls
        var count = new AtomicLong(5);
        base = spy(base);
        when(base.getCreateCount()).thenAnswer(args -> count.getAndAdd(2));

        enqueueAppcLcm("restart", "restart");
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        clMgtQueue.get(0).setAai(Map.of("generic-vnf.vnf-id", "duplicate-VNF"));
        clMgtQueue.get(1).setAai(Map.of("generic-vnf.vnf-id", "vCPE_Infrastructure_vGMUX_demo_app"));

        base.testDuplicatesEvents();

        assertEquals(0, permitCount);
        assertEquals(2, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial events
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
        verify(topics, times(2)).inject(eq(BaseTest.DCAE_TOPIC), any(), any());

        // two restarts
        verify(topics, times(2)).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
    }

    @Test
    void testTestVcpeSunnyDayCompliant() {
        checkAppcLcmPolicy("restart", base::testVcpeSunnyDayCompliant);
    }

    @Test
    void testTestVcpeOnsetFloodPrevention() {
        enqueueAppcLcm("restart");
        enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        base.testVcpeOnsetFloodPrevention();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial events
        verify(topics, times(3)).inject(eq(BaseTest.DCAE_TOPIC), any());

        // one restart
        verify(topics).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
    }

    @Test
    void testTestVdnsSunnyDayCompliant() {
        checkHttpPolicy(base::testVdnsSunnyDayCompliant);
    }

    @Test
    void testTestVdnsRainyDayCompliant() {
        checkHttpPolicyCompliantFailure(base::testVdnsRainyDayCompliant);
    }

    @Test
    void testTestVfwSunnyDayCompliant() {
        checkAppcLegacyPolicy("ModifyConfig", base::testVfwSunnyDayCompliant);
    }

    @Test
    void testTestVfwRainyDayOverallTimeout() {
        checkAppcLegacyPolicyFinalFailure("ModifyConfig", base::testVfwRainyDayOverallTimeout);
    }

    @Test
    void testTestVfwRainyDayCompliantTimeout() {
        checkAppcLegacyPolicyFinalFailure("ModifyConfig", base::testVfwRainyDayCompliantTimeout);
    }

    @Test
    void testTestVpciSunnyDayCompliant() {
        checkSdnrPolicy("ModifyConfig", base::testVpciSunnyDayCompliant);
    }

    @Test
    void testTestVsonhSunnyDayCompliant() {
        checkSdnrPolicy("ModifyConfigANR", base::testVsonhSunnyDayCompliant);
    }

    protected void checkAppcLcmPolicy(String operation, Runnable test) {
        enqueueAppcLcm(operation);
        enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());

        // reply to each APPC request
        verify(topics).inject(eq(BaseTest.APPC_LCM_WRITE_TOPIC), any(), any());
    }

    protected void checkAppcLegacyPolicy(String operation, Runnable test) {
        enqueueAppcLegacy(operation);
        enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());

        // reply to each APPC request
        verify(topics).inject(eq(BaseTest.APPC_CL_TOPIC), any(), any());
    }

    protected void checkAppcLegacyPolicyOperationFailure(String operation, Runnable test) {
        enqueueAppcLegacy(operation);
        enqueueClMgt(ControlLoopNotificationType.OPERATION_FAILURE);
        enqueueClMgt(ControlLoopNotificationType.FINAL_FAILURE);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());

        // reply to each APPC request
        verify(topics).inject(eq(BaseTest.APPC_CL_TOPIC), any(), any());
    }

    protected void checkAppcLegacyPolicyFinalFailure(String operation, Runnable test) {
        enqueueAppcLegacy(operation);
        enqueueClMgt(ControlLoopNotificationType.FINAL_FAILURE);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(appcLcmQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());

        // There were no requests sent
    }

    protected void checkSdnrPolicy(String operation, Runnable test) {
        enqueueSdnr(operation);
        enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(sdnrQueue.isEmpty());
        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());

        // reply to each SDNR request
        verify(topics).inject(eq(BaseTest.SDNR_CL_RSP_TOPIC), any(), any());
    }

    protected void checkHttpPolicy(Runnable test) {
        enqueueClMgt(ControlLoopNotificationType.OPERATION_SUCCESS);
        enqueueClMgt(ControlLoopNotificationType.FINAL_SUCCESS);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
    }

    protected void checkHttpPolicyCompliantFailure(Runnable test) {
        enqueueClMgt(ControlLoopNotificationType.OPERATION_FAILURE);
        enqueueClMgt(ControlLoopNotificationType.FINAL_FAILURE);

        test.run();

        assertEquals(1, permitCount);
        assertEquals(1, finalCount);

        assertTrue(clMgtQueue.isEmpty());

        // initial event
        verify(topics).inject(eq(BaseTest.DCAE_TOPIC), any());
    }

    private void enqueueClMgt(ControlLoopNotificationType type) {
        var notif = new VirtualControlLoopNotification();
        notif.setNotification(type);
        notif.setPolicyName(POLICY_NAME + ".EVENT.MANAGER.FINAL");

        clMgtQueue.add(notif);
    }

    private void enqueueAppcLcm(String... operationNames) {
        for (var oper : operationNames) {
            var req = new AppcLcmDmaapWrapper();
            req.setRpcName(oper);

            var body = new AppcLcmBody();
            req.setBody(body);

            var input = new AppcLcmInput();
            body.setInput(input);

            var header = new AppcLcmCommonHeader();
            input.setCommonHeader(header);

            header.setSubRequestId("my-subrequest-id");

            appcLcmQueue.add(req);
        }
    }

    private void enqueueAppcLegacy(String... operationNames) {
        for (var oper : operationNames) {
            var req = new Request();
            req.setAction(oper);

            var header = new CommonHeader();
            req.setCommonHeader(header);

            header.setSubRequestId("my-subrequest-id");

            appcLegacyQueue.add(req);
        }
    }

    private void enqueueSdnr(String... operationNames) {
        for (String oper : operationNames) {
            var pcimessage = new PciMessage();
            var req = new PciRequest();
            var body = new PciBody();
            body.setInput(req);
            pcimessage.setBody(body);
            pcimessage.getBody().getInput().setAction(oper);
            var header = new PciCommonHeader();
            pcimessage.getBody().getInput().setCommonHeader(header);

            header.setSubRequestId("my-subrequest-id");

            sdnrQueue.add(pcimessage);
        }
    }

    private HttpClients makeHttpClients() {
        return httpClients;
    }

    private Simulators makeSim() {
        return simulators;
    }

    private Topics makeTopics() {
        return topics;
    }

    /*
     * We don't want junit trying to run this, so it's marked "Ignore".
     */
    @Disabled
    private class MyTest extends BaseTest {

        @Override
        protected void waitForLockAndPermit(ToscaPolicy policy, Listener<VirtualControlLoopNotification> policyClMgt) {
            permitCount++;
        }

        @Override
        protected VirtualControlLoopNotification waitForFinal(ToscaPolicy policy,
                        Listener<VirtualControlLoopNotification> policyClMgt, ControlLoopNotificationType finalType) {
            finalCount++;
            return policyClMgt.await(notif -> notif.getNotification() == finalType);
        }
    }
}