2 * Copyright (c) 2010-2023 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.revogi.internal.udp;
15 import static org.hamcrest.CoreMatchers.equalTo;
16 import static org.hamcrest.CoreMatchers.is;
17 import static org.hamcrest.MatcherAssert.assertThat;
18 import static org.mockito.ArgumentMatchers.any;
19 import static org.mockito.Mockito.doAnswer;
20 import static org.mockito.Mockito.doThrow;
21 import static org.mockito.Mockito.mock;
22 import static org.mockito.Mockito.times;
23 import static org.mockito.Mockito.verify;
25 import java.io.IOException;
26 import java.net.DatagramPacket;
27 import java.net.InetAddress;
28 import java.net.SocketTimeoutException;
29 import java.util.Collections;
30 import java.util.List;
31 import java.util.concurrent.CompletableFuture;
32 import java.util.concurrent.ExecutionException;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.junit.jupiter.api.Test;
36 import org.openhab.core.net.NetUtil;
39 * @author Andi Bräu - Initial contribution
42 public class UdpSenderServiceTest {
44 private final DatagramSocketWrapper datagramSocketWrapper = mock(DatagramSocketWrapper.class);
46 private final UdpSenderService udpSenderService = new UdpSenderService(datagramSocketWrapper, 1L);
48 private final int numberOfInterfaces = NetUtil.getAllBroadcastAddresses().size();
51 public void testTimeout() throws IOException, ExecutionException, InterruptedException {
53 doThrow(new SocketTimeoutException()).when(datagramSocketWrapper).receiveAnswer(any());
56 CompletableFuture<List<UdpResponseDTO>> list = udpSenderService.broadcastUdpDatagram("send something");
59 assertThat(list.get(), equalTo(Collections.emptyList()));
60 verify(datagramSocketWrapper, times(numberOfInterfaces * 2)).receiveAnswer(any());
64 public void testOneAnswer() throws IOException, ExecutionException, InterruptedException {
66 byte[] receivedBuf = "valid answer".getBytes();
67 doAnswer(invocation -> {
68 DatagramPacket argument = invocation.getArgument(0);
69 argument.setData(receivedBuf);
70 argument.setAddress(InetAddress.getLocalHost());
72 }).doThrow(new SocketTimeoutException()).when(datagramSocketWrapper).receiveAnswer(any());
75 CompletableFuture<List<UdpResponseDTO>> future = udpSenderService.broadcastUdpDatagram("send something");
78 List<UdpResponseDTO> udpResponses = future.get();
79 assertThat(udpResponses.get(0).getAnswer(), is("valid answer"));
80 verify(datagramSocketWrapper, times(1 + 2 * numberOfInterfaces)).receiveAnswer(any());