]> git.basschouten.com Git - openhab-addons.git/blob
81e8ce620be6ceaa6d839b5623f54bcb9f3a7e20
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.network.internal.dhcp;
14
15 import static org.hamcrest.CoreMatchers.*;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.junit.jupiter.api.Assumptions.assumeTrue;
18 import static org.mockito.ArgumentMatchers.eq;
19 import static org.mockito.Mockito.*;
20
21 import java.io.IOException;
22 import java.net.InetAddress;
23 import java.net.SocketException;
24
25 import org.junit.jupiter.api.Test;
26 import org.openhab.binding.network.internal.dhcp.DHCPPacket.BadPacketException;
27
28 /**
29  * Tests cases for DHCP related functionality
30  *
31  * @author David Graeff - Initial contribution
32  */
33 public class DHCPTest {
34     @Test
35     public void testService() throws SocketException {
36         String testIP = "10.1.2.3";
37         IPRequestReceivedCallback dhcpListener = mock(IPRequestReceivedCallback.class);
38
39         // if this is not the case this test is not very useful, we don't always have the static field under control.
40         assumeTrue(DHCPListenService.instance == null);
41         DHCPListenService.register(testIP, dhcpListener);
42         assertThat(DHCPListenService.instance, is(notNullValue()));
43         DHCPListenService.unregister(testIP);
44         assertThat(DHCPListenService.instance, is(nullValue()));
45     }
46
47     @Test
48     public void testReceivePacketCallback() throws BadPacketException, IOException {
49         String testIP = "10.1.2.3";
50         InetAddress testAddress = InetAddress.getByName(testIP);
51         IPRequestReceivedCallback dhcpListener = mock(IPRequestReceivedCallback.class);
52         DHCPPacketListenerServer s = new DHCPPacketListenerServer(dhcpListener);
53         s.receivePacket(new DHCPPacket(new byte[] { DHCPPacket.DHCPREQUEST }, testAddress.getAddress()), testAddress);
54         // Test case if DHCP packet does not contain a DHO_DHCP_REQUESTED_ADDRESS option.
55         // The destination IP should be deducted by the UDP address in this case
56         s.receivePacket(new DHCPPacket(new byte[] { DHCPPacket.DHCPREQUEST }, null), testAddress);
57         verify(dhcpListener, times(2)).dhcpRequestReceived(eq(testIP));
58     }
59 }