aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/test/java/org/onap/policy/pap/main/comm/RequestDataTest.java
blob: 28e5cf9698c0a744a2eae9ee1faa055077ddc293 (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
/*
 * ============LICENSE_START=======================================================
 * ONAP PAP
 * ================================================================================
 * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.pap.main.comm;

import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
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.Queue;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.listeners.RequestIdDispatcher;
import org.onap.policy.common.endpoints.listeners.TypedMessageListener;
import org.onap.policy.common.utils.services.ServiceManager;
import org.onap.policy.models.pdp.concepts.PdpMessage;
import org.onap.policy.models.pdp.concepts.PdpStateChange;
import org.onap.policy.models.pdp.concepts.PdpStatus;
import org.onap.policy.models.pdp.enums.PdpState;
import org.onap.policy.pap.main.PapConstants;
import org.onap.policy.pap.main.comm.msgdata.MessageData;
import org.onap.policy.pap.main.parameters.RequestDataParams;
import org.powermock.reflect.Whitebox;

public class RequestDataTest {
    private static final String PDP1 = "pdp_1";
    private static final String MY_MSG_TYPE = "my-type";

    private MyRequestData reqdata;
    private Publisher pub;
    private RequestIdDispatcher<PdpStatus> disp;
    private Object lock;
    private TimerManager timers;
    private TimerManager.Timer timer;
    private MyMessageData msgdata;
    private Queue<QueueToken<PdpMessage>> queue;
    private PdpStatus response;

    /**
     * Sets up.
     */
    @Before
    @SuppressWarnings("unchecked")
    public void setUp() {
        pub = mock(Publisher.class);
        disp = mock(RequestIdDispatcher.class);
        lock = new Object();
        timers = mock(TimerManager.class);
        timer = mock(TimerManager.Timer.class);
        msgdata = new MyMessageData(PDP1);
        queue = new LinkedList<>();
        response = new PdpStatus();

        doAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                queue.add(invocation.getArgumentAt(0, QueueToken.class));
                return null;
            }
        }).when(pub).enqueue(any());

        when(timers.register(any(), any())).thenReturn(timer);

        reqdata = new MyRequestData(
                        new RequestDataParams().setModifyLock(lock).setPublisher(pub).setResponseDispatcher(disp));

        reqdata.setName(PDP1);

        msgdata = spy(msgdata);
        reqdata = spy(reqdata);
    }

    @Test
    public void testRequestData_Invalid() {
        // null params
        assertThatThrownBy(() -> new MyRequestData(null)).isInstanceOf(NullPointerException.class);

        // invalid params
        assertThatIllegalArgumentException().isThrownBy(() -> new MyRequestData(new RequestDataParams()));
    }

    @Test
    public void testStartPublishing() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        verify(disp).register(eq(msgdata.getMessage().getRequestId()), any());
        verify(timers).register(eq(PDP1), any());
        verify(pub).enqueue(any());

        QueueToken<PdpMessage> token = queue.poll();
        assertNotNull(token);
        assertSame(msgdata.getMessage(), token.get());


        // invoking start() again has no effect - invocation counts remain the same
        reqdata.startPublishing();
        verify(disp, times(1)).register(eq(msgdata.getMessage().getRequestId()), any());
        verify(timers, times(1)).register(eq(PDP1), any());
        verify(pub, times(1)).enqueue(any());
    }

    @Test
    public void testStopPublishing() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();
        reqdata.stopPublishing();

        verify(disp).unregister(msgdata.getMessage().getRequestId());
        verify(timer).cancel();


        // invoking stop() again has no effect - invocation counts remain the same
        reqdata.stopPublishing();

        verify(disp, times(1)).unregister(msgdata.getMessage().getRequestId());
        verify(timer, times(1)).cancel();
    }

    @Test
    public void testConfigure() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        verify(disp).register(eq(msgdata.getMessage().getRequestId()), any());
        verify(timers).register(eq(PDP1), any());
        verify(pub).enqueue(any());

        ServiceManager svcmgr = Whitebox.getInternalState(reqdata, "svcmgr");
        assertEquals(PDP1 + " " + MY_MSG_TYPE, svcmgr.getName());


        // bump this so we can verify that it is reset by configure()
        reqdata.bumpRetryCount();

        reqdata.configure(msgdata);
        assertEquals(0, getRetryCount());
    }

    @Test
    public void testEnqueue() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        // replace the message with a new message
        reqdata.stopPublishing();
        MyMessageData msgdata2 = new MyMessageData(PDP1);
        reqdata.configure(msgdata2);
        reqdata.startPublishing();

        // should still only be one token in the queue
        QueueToken<PdpMessage> token = queue.poll();
        assertNull(queue.poll());
        assertNotNull(token);
        assertSame(msgdata2.getMessage(), token.get());

        // null out the token
        token.replaceItem(null);

        // enqueue a new message
        reqdata.stopPublishing();
        MyMessageData msgdata3 = new MyMessageData(PDP1);
        reqdata.configure(msgdata3);
        reqdata.startPublishing();

        // a new token should have been placed in the queue
        QueueToken<PdpMessage> token2 = queue.poll();
        assertTrue(token != token2);
        assertNull(queue.poll());
        assertNotNull(token2);
        assertSame(msgdata3.getMessage(), token2.get());
    }

    @Test
    public void testResetRetryCount_testBumpRetryCount() {
        when(msgdata.getMaxRetryCount()).thenReturn(2);

        reqdata.configure(msgdata);

        assertEquals(0, getRetryCount());
        assertTrue(reqdata.bumpRetryCount());
        assertTrue(reqdata.bumpRetryCount());

        // limit should now be reached and it should go no further
        assertFalse(reqdata.bumpRetryCount());
        assertFalse(reqdata.bumpRetryCount());

        assertEquals(2, getRetryCount());

        reqdata.resetRetryCount();
        assertEquals(0, getRetryCount());
    }

    @Test
    public void testRetryCountExhausted() {
        reqdata.configure(msgdata);

        reqdata.retryCountExhausted();

        verify(reqdata).allCompleted();
    }

    @Test
    public void testProcessResponse() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        invokeProcessResponse();

        verify(reqdata).stopPublishing();
        verify(msgdata).checkResponse(response);
        verify(msgdata).completed();
    }

    @Test
    public void testProcessResponse_NotPublishing() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        reqdata.stopPublishing();

        invokeProcessResponse();

        // only invocation should have been the one before calling invokeProcessResponse()
        verify(reqdata, times(1)).stopPublishing();

        verify(msgdata, never()).checkResponse(response);
        verify(msgdata, never()).completed();
    }

    @Test
    public void testProcessResponse_NotActive() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        when(reqdata.isActive()).thenReturn(false);

        invokeProcessResponse();

        // it should still stop publishing
        verify(reqdata).stopPublishing();

        verify(msgdata, never()).checkResponse(response);
        verify(msgdata, never()).completed();
    }

    @Test
    public void testProcessResponse_ResponseFailed() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        when(msgdata.checkResponse(response)).thenReturn("failed");

        invokeProcessResponse();

        verify(reqdata).stopPublishing();
        verify(msgdata).checkResponse(response);

        verify(msgdata, never()).completed();
        verify(msgdata).mismatch("failed");
    }

    @Test
    public void testHandleTimeout() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        // remove it from the queue
        queue.poll().replaceItem(null);

        invokeTimeoutHandler();

        // count should have been bumped
        assertEquals(1, getRetryCount());

        // should have invoked startPublishing() a second time
        verify(reqdata, times(2)).startPublishing();
    }

    @Test
    public void testHandleTimeout_NotPublishing() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        reqdata.stopPublishing();

        invokeTimeoutHandler();

        // should NOT have invoked startPublishing() a second time
        verify(reqdata, times(1)).startPublishing();
        verify(reqdata, never()).retryCountExhausted();
    }

    @Test
    public void testHandleTimeout_NotActive() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        when(reqdata.isActive()).thenReturn(false);

        invokeTimeoutHandler();

        // should NOT have invoked startPublishing() a second time
        verify(reqdata, times(1)).startPublishing();
        verify(reqdata, never()).retryCountExhausted();
    }

    @Test
    public void testHandleTimeout_StillInQueue() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        reqdata.bumpRetryCount();

        invokeTimeoutHandler();

        // count should reset the count
        assertEquals(0, getRetryCount());

        // should have invoked startPublishing() a second time
        verify(reqdata, times(2)).startPublishing();
    }

    @Test
    public void testHandleTimeout_RetryExhausted() {
        reqdata.configure(msgdata);
        reqdata.startPublishing();

        // exhaust the count
        reqdata.bumpRetryCount();
        reqdata.bumpRetryCount();
        reqdata.bumpRetryCount();

        // remove it from the queue
        queue.poll().replaceItem(null);

        invokeTimeoutHandler();

        // should NOT have invoked startPublishing() a second time
        verify(reqdata, times(1)).startPublishing();

        verify(reqdata).retryCountExhausted();
    }

    @Test
    public void testGetName_testSetName() {
        reqdata.setName("abc");
        assertEquals("abc", reqdata.getName());
    }

    @Test
    public void testGetWrapper() {
        reqdata.configure(msgdata);
        assertSame(msgdata, reqdata.getWrapper());
    }

    /**
     * Gets the retry count from the data.
     * @return the current retry count
     */
    private int getRetryCount() {
        return Whitebox.getInternalState(reqdata, "retryCount");
    }

    /**
     * Gets the listener that was registered with the dispatcher and invokes it.
     */
    @SuppressWarnings("unchecked")
    private void invokeProcessResponse() {
        @SuppressWarnings("rawtypes")
        ArgumentCaptor<TypedMessageListener> processResp = ArgumentCaptor.forClass(TypedMessageListener.class);

        verify(disp).register(any(), processResp.capture());

        processResp.getValue().onTopicEvent(CommInfrastructure.NOOP, PapConstants.TOPIC_POLICY_PDP_PAP, response);
    }

    /**
     * Gets the timeout handler that was registered with the timer manager and invokes it.
     */
    @SuppressWarnings("unchecked")
    private void invokeTimeoutHandler() {
        @SuppressWarnings("rawtypes")
        ArgumentCaptor<Consumer> timeoutHdlr = ArgumentCaptor.forClass(Consumer.class);

        verify(timers).register(any(), timeoutHdlr.capture());

        timeoutHdlr.getValue().accept(PDP1);
    }

    private class MyRequestData extends RequestData {

        public MyRequestData(RequestDataParams params) {
            super(params);
        }

        @Override
        protected boolean isActive() {
            return true;
        }

        @Override
        protected void allCompleted() {
            // do nothing
        }
    }

    private class MyMessageData extends MessageData {

        public MyMessageData(String pdpName) {
            super(new PdpStateChange(), 1, timers);

            PdpStateChange msg = (PdpStateChange) getMessage();
            msg.setName(pdpName);
            msg.setState(PdpState.ACTIVE);
        }

        @Override
        public String getType() {
            return MY_MSG_TYPE;
        }

        @Override
        public void mismatch(String reason) {
            // do nothing
        }

        @Override
        public void completed() {
            // do nothing
        }

        @Override
        public String checkResponse(PdpStatus response) {
            // always valid - return null
            return null;
        }
    }
}