aboutsummaryrefslogtreecommitdiffstats
path: root/policy-endpoints/src/test/java/org/onap/policy/common/endpoints/event/comm/bus/internal/SingleThreadedBusTopicSourceTest.java
blob: eaeafef6fa716de39113882448e94b88cca32c6a (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
/*
 * ============LICENSE_START=======================================================
 * policy-endpoints
 * ================================================================================
 * Copyright (C) 2018 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.common.endpoints.event.comm.bus.internal;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Arrays;
import java.util.Collections;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
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.event.comm.TopicListener;
import org.onap.policy.common.endpoints.event.comm.bus.BusTopicTestBase;
import org.onap.policy.common.endpoints.event.comm.bus.internal.BusConsumer.FilterableBusConsumer;

public class SingleThreadedBusTopicSourceTest extends BusTopicTestBase {
    private Thread thread;
    private BusConsumer cons;
    private TopicListener listener;
    private SingleThreadedBusTopicSourceImpl source;

    /**
     * Creates the object to be tested, as well as various mocks.
     */
    @Before
    public void setUp() {
        super.setUp();

        thread = mock(Thread.class);
        cons = mock(BusConsumer.class);
        listener = mock(TopicListener.class);
        source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build());
    }

    @After
    public void tearDown() {
        source.shutdown();
    }

    @Test
    public void testRegister() {
        source.register(listener);
        assertEquals(1, source.initCount);
        source.offer(MY_MESSAGE);
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE);

        // register another - should not re-init
        TopicListener listener2 = mock(TopicListener.class);
        source.register(listener2);
        assertEquals(1, source.initCount);
        source.offer(MY_MESSAGE + "z");
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE + "z");
        verify(listener2).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE + "z");

        // re-register - should not re-init
        source.register(listener);
        assertEquals(1, source.initCount);
        source.offer(MY_MESSAGE2);
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE2);

        // lock & register - should not init
        source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build());
        source.lock();
        source.register(listener);
        assertEquals(0, source.initCount);

        // exception during init
        source = new SingleThreadedBusTopicSourceImpl(makeBuilder().build());
        source.initEx = true;
        source.register(listener);
    }

    @Test
    public void testUnregister() {
        TopicListener listener2 = mock(TopicListener.class);
        source.register(listener);
        source.register(listener2);

        // unregister first listener - should NOT invoke close
        source.unregister(listener);
        verify(cons, never()).close();
        assertEquals(Arrays.asList(listener2), source.snapshotTopicListeners());

        // unregister same listener - should not invoke close
        source.unregister(listener);
        verify(cons, never()).close();
        assertEquals(Arrays.asList(listener2), source.snapshotTopicListeners());

        // unregister second listener - SHOULD invoke close
        source.unregister(listener2);
        verify(cons).close();
        assertTrue(source.snapshotTopicListeners().isEmpty());

        // unregister same listener - should not invoke close again
        source.unregister(listener2);
        verify(cons).close();
        assertTrue(source.snapshotTopicListeners().isEmpty());
    }

    @Test
    public void testToString() {
        assertTrue(source.toString().startsWith("SingleThreadedBusTopicSource ["));
    }

    @Test
    public void testMakePollerThread() {
        SingleThreadedBusTopicSource source2 = new SingleThreadedBusTopicSource(makeBuilder().build()) {
            @Override
            public CommInfrastructure getTopicCommInfrastructure() {
                return CommInfrastructure.NOOP;
            }

            @Override
            public void init() throws MalformedURLException {
                // do nothing
            }
        };
        
        assertNotNull(source2.makePollerThread());
    }

    @Test
    public void testSingleThreadedBusTopicSource() {
        // verify that different wrappers can be built
        new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerGroup(null).build());
        new SingleThreadedBusTopicSourceImpl(makeBuilder().consumerInstance(null).build());
        new SingleThreadedBusTopicSourceImpl(makeBuilder().fetchTimeout(-1).build());
        new SingleThreadedBusTopicSourceImpl(makeBuilder().fetchLimit(-1).build());
    }

    @Test
    public void testStart() {
        source.start();
        assertTrue(source.isAlive());
        assertEquals(1, source.initCount);
        verify(thread).start();

        // attempt to start again - nothing should be invoked again
        source.start();
        assertTrue(source.isAlive());
        assertEquals(1, source.initCount);
        verify(thread).start();

        // stop & re-start
        source.stop();
        source.start();
        assertTrue(source.isAlive());
        assertEquals(2, source.initCount);
        verify(thread, times(2)).start();
    }

    @Test(expected = IllegalStateException.class)
    public void testStart_Locked() {
        source.lock();
        source.start();
    }

    @Test(expected = IllegalStateException.class)
    public void testStart_InitEx() {
        source.initEx = true;
        source.start();
    }

    @Test
    public void testStop() {
        source.start();
        source.stop();
        verify(cons).close();

        // stop it again - not re-closed
        source.stop();
        verify(cons).close();

        // start & stop again, but with an exception
        doThrow(new RuntimeException(EXPECTED)).when(cons).close();
        source.start();
        source.stop();
    }

    @Test
    public void testRun() throws Exception {
        source.register(listener);

        /*
         * Die in the middle of fetching messages. Also, throw an exception during the
         * first fetch attempt.
         */
        when(cons.fetch()).thenAnswer(new Answer<Iterable<String>>() {
            int count = 0;

            @Override
            public Iterable<String> answer(InvocationOnMock invocation) throws Throwable {
                if (++count > 1) {
                    source.alive = false;
                    return Arrays.asList(MY_MESSAGE, MY_MESSAGE2);

                } else {
                    throw new IOException(EXPECTED);
                }
            }
        });
        source.alive = true;
        source.run();
        assertEquals(Arrays.asList(MY_MESSAGE), Arrays.asList(source.getRecentEvents()));
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE);
        verify(listener, never()).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE2);

        /*
         * Die AFTER fetching messages.
         */
        final String msga = "message-A";
        final String msgb = "message-B";
        when(cons.fetch()).thenAnswer(new Answer<Iterable<String>>() {
            int count = 0;

            @Override
            public Iterable<String> answer(InvocationOnMock invocation) throws Throwable {
                if (++count > 1) {
                    source.alive = false;
                    return Collections.emptyList();

                } else {
                    return Arrays.asList(msga, msgb);
                }
            }
        });
        source.alive = true;
        source.run();
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msga);
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, msgb);

        assertEquals(Arrays.asList(MY_MESSAGE, msga, msgb), Arrays.asList(source.getRecentEvents()));
    }

    @Test
    public void testOffer() {
        source.register(listener);
        source.offer(MY_MESSAGE);
        verify(listener).onTopicEvent(CommInfrastructure.NOOP, MY_TOPIC, MY_MESSAGE);
        assertEquals(Arrays.asList(MY_MESSAGE), Arrays.asList(source.getRecentEvents()));
    }

    @Test(expected = IllegalStateException.class)
    public void testOffer_NotStarted() {
        source.offer(MY_MESSAGE);
    }

    @Test
    public void testSetFilter() {
        FilterableBusConsumer filt = mock(FilterableBusConsumer.class);
        cons = filt;

        source.start();
        source.setFilter("my-filter");
        verify(filt).setFilter("my-filter");
    }

    @Test(expected = UnsupportedOperationException.class)
    public void testSetFilter_Unsupported() {
        source.start();
        source.setFilter("unsupported-filter");
    }

    @Test
    public void testGetConsumerGroup() {
        assertEquals(MY_CONS_GROUP, source.getConsumerGroup());
    }

    @Test
    public void testGetConsumerInstance() {
        assertEquals(MY_CONS_INST, source.getConsumerInstance());
    }

    @Test
    public void testShutdown() {
        source.register(listener);

        source.shutdown();
        verify(cons).close();
        assertTrue(source.snapshotTopicListeners().isEmpty());
    }

    @Test
    public void testGetFetchTimeout() {
        assertEquals(MY_FETCH_TIMEOUT, source.getFetchTimeout());
    }

    @Test
    public void testGetFetchLimit() {
        assertEquals(MY_FETCH_LIMIT, source.getFetchLimit());
    }

    /**
     * Implementation of SingleThreadedBusTopicSource that counts the number of times
     * init() is invoked.
     */
    private class SingleThreadedBusTopicSourceImpl extends SingleThreadedBusTopicSource {

        private int initCount = 0;
        private boolean initEx = false;

        public SingleThreadedBusTopicSourceImpl(BusTopicParams busTopicParams) {
            super(busTopicParams);
        }

        @Override
        public CommInfrastructure getTopicCommInfrastructure() {
            return CommInfrastructure.NOOP;
        }

        @Override
        public void init() throws MalformedURLException {
            ++initCount;

            if (initEx) {
                throw new MalformedURLException(EXPECTED);
            }

            consumer = cons;
        }

        @Override
        protected Thread makePollerThread() {
            return thread;
        }

    }
}