]> git.basschouten.com Git - openhab-addons.git/blob
550a59a5c1edb95b4e3b82ddf3993aa11e483ad2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.eclipse.jdt.annotation.NonNullByDefault;
26 import org.junit.jupiter.api.Test;
27 import org.openhab.binding.network.internal.dhcp.DHCPPacket.BadPacketException;
28
29 /**
30  * Tests cases for DHCP related functionality
31  *
32  * @author David Graeff - Initial contribution
33  */
34 @NonNullByDefault
35 public class DHCPTest {
36     @Test
37     public void testService() throws SocketException {
38         String testIP = "10.1.2.3";
39         IPRequestReceivedCallback dhcpListener = mock(IPRequestReceivedCallback.class);
40
41         // if this is not the case this test is not very useful, we don't always have the static field under control.
42         assumeTrue(DHCPListenService.instance == null);
43         DHCPListenService.register(testIP, dhcpListener);
44         assertThat(DHCPListenService.instance, is(notNullValue()));
45         DHCPListenService.unregister(testIP);
46         assertThat(DHCPListenService.instance, is(nullValue()));
47     }
48
49     @Test
50     public void testReceivePacketCallback() throws BadPacketException, IOException {
51         String testIP = "10.1.2.3";
52         InetAddress testAddress = InetAddress.getByName(testIP);
53         IPRequestReceivedCallback dhcpListener = mock(IPRequestReceivedCallback.class);
54         DHCPPacketListenerServer s = new DHCPPacketListenerServer(dhcpListener);
55         s.receivePacket(new DHCPPacket(new byte[] { DHCPPacket.DHCPREQUEST }, testAddress.getAddress()), testAddress);
56         // Test case if DHCP packet does not contain a DHO_DHCP_REQUESTED_ADDRESS option.
57         // The destination IP should be deducted by the UDP address in this case
58         s.receivePacket(new DHCPPacket(new byte[] { DHCPPacket.DHCPREQUEST }, null), testAddress);
59         verify(dhcpListener, times(2)).dhcpRequestReceived(eq(testIP));
60     }
61 }