JUnit Test - LispSouthboundPluginTest
[lispflowmapping.git] / mappingservice / southbound / src / test / java / org / opendaylight / lispflowmapping / southbound / LispSouthboundPluginTest.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, 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.lispflowmapping.southbound;
9
10 import static org.junit.Assert.assertArrayEquals;
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNull;
13
14 import io.netty.bootstrap.Bootstrap;
15 import io.netty.channel.ChannelFuture;
16 import io.netty.channel.EventLoopGroup;
17 import io.netty.channel.socket.DatagramPacket;
18 import io.netty.channel.socket.nio.NioDatagramChannel;
19 import java.lang.reflect.Field;
20 import java.net.InetAddress;
21 import java.net.InetSocketAddress;
22 import java.net.UnknownHostException;
23 import java.nio.ByteBuffer;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27 import org.mockito.ArgumentCaptor;
28 import org.mockito.Mockito;
29 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
30 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
31 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
32 import org.opendaylight.lispflowmapping.lisp.type.LispMessage;
33 import org.opendaylight.lispflowmapping.southbound.lisp.LispSouthboundHandler;
34 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
35 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.IpAddressBinary;
36 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv4AddressBinary;
37 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.inet.binary.types.rev160303.Ipv6AddressBinary;
38 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.MessageType;
39 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddress;
40 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.proto.rev151105.transport.address.TransportAddressBuilder;
41 import org.opendaylight.yang.gen.v1.urn.opendaylight.lfm.lisp.sb.rev150904.OdlLispSbService;
42 import org.powermock.api.mockito.PowerMockito;
43 import org.powermock.core.classloader.annotations.PrepareForTest;
44 import org.powermock.modules.junit4.PowerMockRunner;
45
46 @RunWith(PowerMockRunner.class)
47 @PrepareForTest(NioDatagramChannel.class)
48 public class LispSouthboundPluginTest {
49
50     private static NioDatagramChannel channel;
51     private static NioDatagramChannel xtrChannel;
52     private static LispSouthboundPlugin lispSouthboundPlugin;
53     private static final Bootstrap BOOTSTRAP_MOCK = Mockito.mock(Bootstrap.class);
54
55     private static final String LISP_MAP_REQUEST_PACKET_STRING =
56             "10 00 00 01 3d 8d 2a cd 39 c8 d6 08 00 01 01 02 03 04 00 01 7f 00 00 02 00 20 00 01 7f 00 00 01";
57     private static final String ADDRESS_1 = "0.0.0.0";
58     private static final String ADDRESS_2 = "1.1.1.1";
59     private static final ByteBuffer PACKET = parseHexString(LISP_MAP_REQUEST_PACKET_STRING);
60     private static final int PORT = 9999;
61     private static final byte[] IPV4_BYTES = new byte[]{1, 2, 3, 4};
62     private static final byte[] IPV6_BYTES = new byte[]{11, 11, 22, 22, 33, 33, 44, 44, 55, 55, 66, 66, 77, 77, 88, 88};
63     private static final IpAddressBinary IPV4_BINARY = new IpAddressBinary(new Ipv4AddressBinary(IPV4_BYTES));
64     private static final IpAddressBinary IPV6_BINARY = new IpAddressBinary(new Ipv6AddressBinary(IPV6_BYTES));
65     private static final TransportAddress TRANSPORT_ADDRESS_IPV4 = new TransportAddressBuilder()
66             .setIpAddress(IPV4_BINARY)
67             .setPort(new PortNumber(PORT)).build();
68     private static final TransportAddress TRANSPORT_ADDRESS_IPV6 = new TransportAddressBuilder()
69             .setIpAddress(IPV6_BINARY)
70             .setPort(new PortNumber(PORT)).build();
71
72     @Before
73     public void init() throws NoSuchFieldException, IllegalAccessException, InterruptedException {
74         lispSouthboundPlugin = new LispSouthboundPlugin();
75         channel = PowerMockito.mock(NioDatagramChannel.class);
76         xtrChannel = PowerMockito.mock(NioDatagramChannel.class);
77         injectChannel();
78         injectXtrChannel();
79     }
80
81     /**
82      * Tests {@link LispSouthboundPlugin#handleSerializedLispBuffer} method with ipv4.
83      *
84      * @throws NoSuchFieldException
85      * @throws IllegalAccessException
86      * @throws UnknownHostException
87      */
88     @Test
89     public void handleSerializedLispBufferTest_withIpv4() throws
90             NoSuchFieldException, IllegalAccessException, UnknownHostException {
91         final ArgumentCaptor<DatagramPacket> captor = ArgumentCaptor.forClass(DatagramPacket.class);
92         final InetAddress address = InetAddress.getByAddress(IPV4_BINARY.getIpv4AddressBinary().getValue());
93         final InetSocketAddress inetSocketAddress = new InetSocketAddress(address, PORT);
94
95         // Ensures that NPE is not thrown.
96         Mockito.when(channel.write(Mockito.any())).thenReturn(Mockito.mock(ChannelFuture.class));
97
98         lispSouthboundPlugin.handleSerializedLispBuffer(TRANSPORT_ADDRESS_IPV4, PACKET, MessageType.MapRequest);
99         Mockito.verify(channel).write(captor.capture());
100         Mockito.verify(channel).flush();
101
102         final DatagramPacket result = captor.getValue();
103         assertArrayEquals(PACKET.array(), result.content().array());
104         assertEquals(inetSocketAddress, result.recipient());
105     }
106
107     /**
108      * Tests {@link LispSouthboundPlugin#handleSerializedLispBuffer} method with ipv6.
109      *
110      * @throws NoSuchFieldException
111      * @throws IllegalAccessException
112      * @throws UnknownHostException
113      */
114     @Test
115     public void handleSerializedLispBufferTest_withIpv6() throws
116             NoSuchFieldException, IllegalAccessException, UnknownHostException {
117         final ArgumentCaptor<DatagramPacket> captor = ArgumentCaptor.forClass(DatagramPacket.class);
118         final InetAddress address = InetAddress.getByAddress(IPV6_BINARY.getIpv6AddressBinary().getValue());
119         final InetSocketAddress inetSocketAddress = new InetSocketAddress(address, PORT);
120
121         // Ensures that NPE is not thrown.
122         Mockito.when(channel.write(Mockito.any())).thenReturn(Mockito.mock(ChannelFuture.class));
123
124         lispSouthboundPlugin.handleSerializedLispBuffer(TRANSPORT_ADDRESS_IPV6, PACKET, MessageType.MapRequest);
125         Mockito.verify(channel).write(captor.capture());
126         Mockito.verify(channel).flush();
127
128         final DatagramPacket result = captor.getValue();
129         assertArrayEquals(PACKET.array(), result.content().array());
130         assertEquals(inetSocketAddress, result.recipient());
131     }
132
133     /**
134      * Tests {@link LispSouthboundPlugin#setLispAddress} method - binding address has changed.
135      */
136     @Test
137     public void setLispAddressTest_withEqualAddress() throws NoSuchFieldException, IllegalAccessException {
138         injectField("bootstrap", BOOTSTRAP_MOCK);
139         lispSouthboundPlugin.setLispAddress(ADDRESS_2);
140
141         Mockito.verify(BOOTSTRAP_MOCK).bind(ADDRESS_2, LispMessage.PORT_NUM);
142         Mockito.verify(channel).close();
143     }
144
145     /**
146      * Tests {@link LispSouthboundPlugin#setLispAddress} method - binding address has not changed.
147      */
148     @Test
149     public void setLispAddressTest_withChangedAddress() throws NoSuchFieldException, IllegalAccessException {
150         injectField("bootstrap", BOOTSTRAP_MOCK);
151         lispSouthboundPlugin.setLispAddress(ADDRESS_1);
152
153         Mockito.verifyZeroInteractions(BOOTSTRAP_MOCK);
154         Mockito.verifyZeroInteractions(channel);
155     }
156
157     /**
158      * Tests {@link LispSouthboundPlugin#shouldListenOnXtrPort} method, shouldListenOnXtrPort == true.
159      */
160     @Test
161     public void shouldListenOnXtrPortTest_true() throws NoSuchFieldException, IllegalAccessException {
162         lispSouthboundPlugin.shouldListenOnXtrPort(true);
163
164         Mockito.verify(xtrChannel).close();
165     }
166
167     /**
168      * Tests {@link LispSouthboundPlugin#shouldListenOnXtrPort} method, shouldListenOnXtrPort == false.
169      */
170     @Test
171     public void shouldListenOnXtrPortTest_false() throws NoSuchFieldException, IllegalAccessException {
172         lispSouthboundPlugin.shouldListenOnXtrPort(false);
173
174         Mockito.verifyZeroInteractions(xtrChannel);
175     }
176
177     /**
178      * Tests {@link LispSouthboundPlugin#setXtrPort} method.
179      */
180     @Test
181     public void setXtrPortTest() throws NoSuchFieldException, IllegalAccessException {
182         lispSouthboundPlugin.shouldListenOnXtrPort(true);
183         lispSouthboundPlugin.setXtrPort(PORT);
184
185         Mockito.verify(xtrChannel, Mockito.times(2)).close();
186         assertEquals(PORT, (int) LispSouthboundPluginTest.<Integer>getField("xtrPort"));
187     }
188
189     /**
190      * Tests {@link LispSouthboundPlugin#setNotificationPublishService} method.
191      */
192     @Test
193     public void setNotificationPublishServiceTest() throws NoSuchFieldException, IllegalAccessException {
194         final NotificationPublishService serviceMock = Mockito.mock(NotificationPublishService.class);
195         lispSouthboundPlugin.setNotificationPublishService(serviceMock);
196
197         assertEquals(serviceMock,
198                 LispSouthboundPluginTest.<NotificationPublishService>getField("notificationPublishService"));
199     }
200
201     /**
202      * Tests {@link LispSouthboundPlugin#setRpcRegistryDependency} method.
203      */
204     @Test
205     public void setRpcRegistryDependencyTest() throws NoSuchFieldException, IllegalAccessException {
206         final RpcProviderRegistry registryMock = Mockito.mock(RpcProviderRegistry.class);
207         lispSouthboundPlugin.setRpcRegistryDependency(registryMock);
208
209         assertEquals(registryMock, LispSouthboundPluginTest.<RpcProviderRegistry>getField("rpcRegistry"));
210     }
211
212     /**
213      * Tests {@link LispSouthboundPlugin#close} method.
214      */
215     @Test
216     @SuppressWarnings("unchecked")
217     public void closeTest() throws Exception {
218         EventLoopGroup elgMock = Mockito.mock(EventLoopGroup.class);
219         LispSouthboundPluginTest.injectField("eventLoopGroup", elgMock);
220
221         BindingAwareBroker.RpcRegistration<OdlLispSbService> registrationMock =
222                 Mockito.mock(BindingAwareBroker.RpcRegistration.class);
223         LispSouthboundPluginTest.injectField("sbRpcRegistration", registrationMock);
224
225         LispSouthboundHandler handlerMock = Mockito.mock(LispSouthboundHandler.class);
226         LispSouthboundPluginTest.injectField("lispSouthboundHandler", handlerMock);
227         Mockito.when(channel.close()).thenReturn(Mockito.mock(ChannelFuture.class));
228
229         lispSouthboundPlugin.close();
230
231         Mockito.verify(channel).close();
232         Mockito.verify(elgMock).shutdownGracefully();
233         Mockito.verify(registrationMock).close();
234         Mockito.verify(handlerMock).close();
235         assertNull(getField("lispSouthboundHandler"));
236         assertNull(getField("lispXtrSouthboundHandler"));
237         assertNull(getField("channel"));
238     }
239
240     private static void injectChannel() throws NoSuchFieldException, IllegalAccessException {
241         final Field channelField = LispSouthboundPlugin.class.getDeclaredField("channel");
242         channelField.setAccessible(true);
243         channelField.set(lispSouthboundPlugin, channel);
244     }
245
246     private static void injectXtrChannel() throws NoSuchFieldException, IllegalAccessException {
247         final Field xtrChannelField = LispSouthboundPlugin.class.getDeclaredField("xtrChannel");
248         xtrChannelField.setAccessible(true);
249         xtrChannelField.set(lispSouthboundPlugin, xtrChannel);
250     }
251
252     private static ByteBuffer parseHexString(String packet) {
253         final String[] tokens = packet.split("\\s+");
254         final ByteBuffer buffer = ByteBuffer.allocate(tokens.length);
255         for (String token : tokens) {
256              buffer.put((byte) Integer.parseInt(token, 16));
257         }
258
259         return buffer;
260     }
261
262     private static <T> void injectField(String fieldName, T obj) throws NoSuchFieldException, IllegalAccessException {
263         Field field = LispSouthboundPlugin.class.getDeclaredField(fieldName);
264         field.setAccessible(true);
265         field.set(lispSouthboundPlugin, obj);
266     }
267
268     @SuppressWarnings("unchecked")
269     private static <T> T getField(String fieldName) throws NoSuchFieldException, IllegalAccessException {
270         Field field = LispSouthboundPlugin.class.getDeclaredField(fieldName);
271         field.setAccessible(true);
272
273         return (T) field.get(lispSouthboundPlugin);
274     }
275 }