2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.network.internal.dhcp;
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.*;
21 import java.io.IOException;
22 import java.net.InetAddress;
23 import java.net.SocketException;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.junit.jupiter.api.Test;
27 import org.openhab.binding.network.internal.dhcp.DHCPPacket.BadPacketException;
30 * Tests cases for DHCP related functionality
32 * @author David Graeff - Initial contribution
35 public class DHCPTest {
37 public void testService() throws SocketException {
38 String testIP = "10.1.2.3";
39 IPRequestReceivedCallback dhcpListener = mock(IPRequestReceivedCallback.class);
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()));
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));