Add new Maven module to manage NBI Notifications
[transportpce.git] / nbinotifications / src / test / java / org / opendaylight / transportpce / nbinotifications / consumer / SubscriberTest.java
1 /*
2  * Copyright © 2020 Orange, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.transportpce.nbinotifications.consumer;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertTrue;
12
13 import java.util.Collections;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import org.apache.kafka.clients.consumer.ConsumerRecord;
18 import org.apache.kafka.clients.consumer.MockConsumer;
19 import org.apache.kafka.clients.consumer.OffsetResetStrategy;
20 import org.apache.kafka.common.TopicPartition;
21 import org.junit.Before;
22 import org.junit.Test;
23 import org.opendaylight.transportpce.nbinotifications.utils.NotificationServiceDataUtils;
24 import org.opendaylight.transportpce.test.AbstractTest;
25 import org.opendaylight.yang.gen.v1.nbi.notifications.rev201130.get.notifications.service.output.NotificationService;
26
27 public class SubscriberTest extends AbstractTest {
28     private static final String TOPIC = "topic";
29     private static final int PARTITION = 0;
30     private MockConsumer<String, NotificationService> mockConsumer;
31     private Subscriber subscriber;
32
33     @Before
34     public void setUp() {
35         mockConsumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
36         subscriber = new Subscriber(mockConsumer);
37     }
38
39     @Test
40     public void subscribeServiceShouldBeSuccessful() {
41         // from https://www.baeldung.com/kafka-mockconsumer
42         ConsumerRecord<String, NotificationService> record = new ConsumerRecord<String, NotificationService>(
43                 TOPIC, PARTITION, 0L, "key", NotificationServiceDataUtils.buildReceivedEvent());
44         mockConsumer.schedulePollTask(() -> {
45             mockConsumer.rebalance(Collections.singletonList(new TopicPartition(TOPIC, PARTITION)));
46             mockConsumer.addRecord(record);
47         });
48
49         Map<TopicPartition, Long> startOffsets = new HashMap<>();
50         TopicPartition tp = new TopicPartition(TOPIC, PARTITION);
51         startOffsets.put(tp, 0L);
52         mockConsumer.updateBeginningOffsets(startOffsets);
53         List<NotificationService> result = subscriber.subscribeService(TOPIC);
54         assertEquals("There should be 1 record", 1, result.size());
55         assertTrue("Consumer should be closed", mockConsumer.closed());
56     }
57 }