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.boschshc.internal.devices.bridge;
15 import static org.junit.jupiter.api.Assertions.*;
16 import static org.mockito.ArgumentMatchers.*;
17 import static org.mockito.Mockito.*;
19 import java.nio.ByteBuffer;
20 import java.nio.charset.StandardCharsets;
21 import java.util.Collections;
22 import java.util.List;
23 import java.util.concurrent.AbstractExecutorService;
24 import java.util.concurrent.Callable;
25 import java.util.concurrent.Delayed;
26 import java.util.concurrent.ExecutionException;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.concurrent.ScheduledFuture;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.TimeoutException;
31 import java.util.function.Consumer;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.eclipse.jetty.client.api.Request;
37 import org.eclipse.jetty.client.api.Response;
38 import org.eclipse.jetty.client.api.Response.CompleteListener;
39 import org.eclipse.jetty.client.api.Result;
40 import org.eclipse.jetty.client.util.BufferingResponseListener;
41 import org.eclipse.jetty.http.HttpMethod;
42 import org.junit.jupiter.api.AfterEach;
43 import org.junit.jupiter.api.BeforeEach;
44 import org.junit.jupiter.api.Test;
45 import org.junit.jupiter.api.extension.ExtendWith;
46 import org.mockito.ArgumentCaptor;
47 import org.mockito.Mock;
48 import org.mockito.junit.jupiter.MockitoExtension;
49 import org.openhab.binding.boschshc.internal.devices.bridge.dto.DeviceServiceData;
50 import org.openhab.binding.boschshc.internal.devices.bridge.dto.LongPollResult;
51 import org.openhab.binding.boschshc.internal.devices.bridge.dto.SubscribeResult;
52 import org.openhab.binding.boschshc.internal.exceptions.BoschSHCException;
53 import org.openhab.binding.boschshc.internal.exceptions.LongPollingFailedException;
55 import com.google.gson.JsonObject;
58 * Unit tests for {@link LongPolling}.
60 * @author David Pace - Initial contribution
64 @ExtendWith(MockitoExtension.class)
65 class LongPollingTest {
68 * A dummy implementation of {@link ScheduledFuture}.
70 * This is required because we can not return <code>null</code> in the executor service test implementation (see
73 * @author David Pace - Initial contribution
75 * @param <T> The result type returned by this Future
77 private static class NullScheduledFuture<T> implements ScheduledFuture<T> {
80 public long getDelay(@Nullable TimeUnit unit) {
85 public int compareTo(@Nullable Delayed o) {
90 public boolean cancel(boolean mayInterruptIfRunning) {
95 public boolean isCancelled() {
100 public boolean isDone() {
105 public T get() throws InterruptedException, ExecutionException {
110 public T get(long timeout, @Nullable TimeUnit unit)
111 throws InterruptedException, ExecutionException, TimeoutException {
117 * Executor service implementation that runs all runnables in the same thread in order to enable deterministic
120 * @author David Pace - Initial contribution
123 private static class SameThreadExecutorService extends AbstractExecutorService implements ScheduledExecutorService {
125 private volatile boolean terminated;
128 public void shutdown() {
132 @NonNullByDefault({})
134 public List<Runnable> shutdownNow() {
135 return Collections.emptyList();
139 public boolean isShutdown() {
144 public boolean isTerminated() {
149 public boolean awaitTermination(long timeout, @Nullable TimeUnit unit) throws InterruptedException {
155 public void execute(@Nullable Runnable command) {
156 if (command != null) {
157 // execute in the same thread in unit tests
163 public ScheduledFuture<?> schedule(@Nullable Runnable command, long delay, @Nullable TimeUnit unit) {
164 // not used in this tests
165 return new NullScheduledFuture<Object>();
169 public <V> ScheduledFuture<V> schedule(@Nullable Callable<V> callable, long delay, @Nullable TimeUnit unit) {
170 return new NullScheduledFuture<V>();
174 public ScheduledFuture<?> scheduleAtFixedRate(@Nullable Runnable command, long initialDelay, long period,
175 @Nullable TimeUnit unit) {
176 if (command != null) {
179 return new NullScheduledFuture<Object>();
183 public ScheduledFuture<?> scheduleWithFixedDelay(@Nullable Runnable command, long initialDelay, long delay,
184 @Nullable TimeUnit unit) {
185 if (command != null) {
188 return new NullScheduledFuture<Object>();
192 private @NonNullByDefault({}) LongPolling fixture;
194 private @NonNullByDefault({}) BoschHttpClient httpClient;
196 private @Mock @NonNullByDefault({}) Consumer<@NonNull LongPollResult> longPollHandler;
198 private @Mock @NonNullByDefault({}) Consumer<@NonNull Throwable> failureHandler;
202 fixture = new LongPolling(new SameThreadExecutorService(), longPollHandler, failureHandler);
203 httpClient = mock(BoschHttpClient.class);
207 void start() throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
208 // when(httpClient.getBoschSmartHomeUrl(anyString())).thenCallRealMethod();
209 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
211 Request subscribeRequest = mock(Request.class);
212 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
213 argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
214 SubscribeResult subscribeResult = new SubscribeResult();
215 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
217 Request longPollRequest = mock(Request.class);
218 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
219 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
221 fixture.start(httpClient);
223 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
224 verify(longPollRequest).send(completeListener.capture());
226 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
228 String longPollResultJSON = "{\"result\":[{\"path\":\"/devices/hdm:HomeMaticIP:3014F711A0001916D859A8A9/services/PowerSwitch\",\"@type\":\"DeviceServiceData\",\"id\":\"PowerSwitch\",\"state\":{\"@type\":\"powerSwitchState\",\"switchState\":\"ON\"},\"deviceId\":\"hdm:HomeMaticIP:3014F711A0001916D859A8A9\"}],\"jsonrpc\":\"2.0\"}\n";
229 Response response = mock(Response.class);
230 bufferingResponseListener.onContent(response,
231 ByteBuffer.wrap(longPollResultJSON.getBytes(StandardCharsets.UTF_8)));
233 Result result = mock(Result.class);
234 bufferingResponseListener.onComplete(result);
236 ArgumentCaptor<LongPollResult> longPollResultCaptor = ArgumentCaptor.forClass(LongPollResult.class);
237 verify(longPollHandler).accept(longPollResultCaptor.capture());
238 LongPollResult longPollResult = longPollResultCaptor.getValue();
239 assertEquals(1, longPollResult.result.size());
240 DeviceServiceData longPollResultItem = longPollResult.result.get(0);
241 assertEquals("hdm:HomeMaticIP:3014F711A0001916D859A8A9", longPollResultItem.deviceId);
242 assertEquals("/devices/hdm:HomeMaticIP:3014F711A0001916D859A8A9/services/PowerSwitch", longPollResultItem.path);
243 assertEquals("PowerSwitch", longPollResultItem.id);
244 JsonObject stateObject = (JsonObject) longPollResultItem.state;
245 assertNotNull(stateObject);
246 assertEquals("ON", stateObject.get("switchState").getAsString());
250 void startSubscriptionFailure()
251 throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
252 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any()))
253 .thenThrow(new ExecutionException("Subscription failed.", null));
255 LongPollingFailedException e = assertThrows(LongPollingFailedException.class, () -> fixture.start(httpClient));
256 assertTrue(e.getMessage().contains("Subscription failed."));
260 void startLongPollFailure() throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
261 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
263 Request request = mock(Request.class);
264 when(httpClient.createRequest(anyString(), same(HttpMethod.POST), any(JsonRpcRequest.class)))
265 .thenReturn(request);
266 SubscribeResult subscribeResult = new SubscribeResult();
267 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
269 Request longPollRequest = mock(Request.class);
270 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
271 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
273 fixture.start(httpClient);
275 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
276 verify(longPollRequest).send(completeListener.capture());
278 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
280 Result result = mock(Result.class);
281 ExecutionException exception = new ExecutionException("test exception", null);
282 when(result.getFailure()).thenReturn(exception);
283 bufferingResponseListener.onComplete(result);
285 ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
286 verify(failureHandler).accept(throwableCaptor.capture());
287 Throwable t = throwableCaptor.getValue();
288 assertEquals("Unexpected exception during long polling request", t.getMessage());
289 assertSame(exception, t.getCause());
293 void startSubscriptionInvalid()
294 throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
295 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
297 Request subscribeRequest = mock(Request.class);
298 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
299 argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
300 SubscribeResult subscribeResult = new SubscribeResult();
301 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
303 Request longPollRequest = mock(Request.class);
304 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
305 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
307 fixture.start(httpClient);
309 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
310 verify(longPollRequest).send(completeListener.capture());
312 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
314 String longPollResultJSON = "{\"jsonrpc\":\"2.0\",\"error\": {\"code\":-32001,\"message\":\"No subscription with id: e8fei62b0-0\"}}\n";
315 Response response = mock(Response.class);
316 bufferingResponseListener.onContent(response,
317 ByteBuffer.wrap(longPollResultJSON.getBytes(StandardCharsets.UTF_8)));
319 Result result = mock(Result.class);
320 bufferingResponseListener.onComplete(result);