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.Scenario;
52 import org.openhab.binding.boschshc.internal.devices.bridge.dto.SubscribeResult;
53 import org.openhab.binding.boschshc.internal.exceptions.BoschSHCException;
54 import org.openhab.binding.boschshc.internal.exceptions.LongPollingFailedException;
56 import com.google.gson.JsonObject;
59 * Unit tests for {@link LongPolling}.
61 * @author David Pace - Initial contribution
65 @ExtendWith(MockitoExtension.class)
66 class LongPollingTest {
69 * A dummy implementation of {@link ScheduledFuture}.
71 * This is required because we can not return <code>null</code> in the executor service test implementation (see
74 * @author David Pace - Initial contribution
76 * @param <T> The result type returned by this Future
78 private static class NullScheduledFuture<T> implements ScheduledFuture<T> {
81 public long getDelay(@Nullable TimeUnit unit) {
86 public int compareTo(@Nullable Delayed o) {
91 public boolean cancel(boolean mayInterruptIfRunning) {
96 public boolean isCancelled() {
101 public boolean isDone() {
106 public T get() throws InterruptedException, ExecutionException {
111 public T get(long timeout, @Nullable TimeUnit unit)
112 throws InterruptedException, ExecutionException, TimeoutException {
118 * Executor service implementation that runs all runnables in the same thread in order to enable deterministic
121 * @author David Pace - Initial contribution
124 private static class SameThreadExecutorService extends AbstractExecutorService implements ScheduledExecutorService {
126 private volatile boolean terminated;
129 public void shutdown() {
133 @NonNullByDefault({})
135 public List<Runnable> shutdownNow() {
136 return Collections.emptyList();
140 public boolean isShutdown() {
145 public boolean isTerminated() {
150 public boolean awaitTermination(long timeout, @Nullable TimeUnit unit) throws InterruptedException {
156 public void execute(@Nullable Runnable command) {
157 if (command != null) {
158 // execute in the same thread in unit tests
164 public ScheduledFuture<?> schedule(@Nullable Runnable command, long delay, @Nullable TimeUnit unit) {
165 // not used in this tests
166 return new NullScheduledFuture<Object>();
170 public <V> ScheduledFuture<V> schedule(@Nullable Callable<V> callable, long delay, @Nullable TimeUnit unit) {
171 return new NullScheduledFuture<V>();
175 public ScheduledFuture<?> scheduleAtFixedRate(@Nullable Runnable command, long initialDelay, long period,
176 @Nullable TimeUnit unit) {
177 if (command != null) {
180 return new NullScheduledFuture<Object>();
184 public ScheduledFuture<?> scheduleWithFixedDelay(@Nullable Runnable command, long initialDelay, long delay,
185 @Nullable TimeUnit unit) {
186 if (command != null) {
189 return new NullScheduledFuture<Object>();
193 private @NonNullByDefault({}) LongPolling fixture;
195 private @NonNullByDefault({}) BoschHttpClient httpClient;
197 private @Mock @NonNullByDefault({}) Consumer<@NonNull LongPollResult> longPollHandler;
199 private @Mock @NonNullByDefault({}) Consumer<@NonNull Throwable> failureHandler;
203 fixture = new LongPolling(new SameThreadExecutorService(), longPollHandler, failureHandler);
204 httpClient = mock(BoschHttpClient.class);
208 void start() throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
209 // when(httpClient.getBoschSmartHomeUrl(anyString())).thenCallRealMethod();
210 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
212 Request subscribeRequest = mock(Request.class);
213 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
214 argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
215 SubscribeResult subscribeResult = new SubscribeResult();
216 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
218 Request longPollRequest = mock(Request.class);
219 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
220 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
222 fixture.start(httpClient);
224 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
225 verify(longPollRequest).send(completeListener.capture());
227 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
229 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";
230 Response response = mock(Response.class);
231 bufferingResponseListener.onContent(response,
232 ByteBuffer.wrap(longPollResultJSON.getBytes(StandardCharsets.UTF_8)));
234 Result result = mock(Result.class);
235 bufferingResponseListener.onComplete(result);
237 ArgumentCaptor<LongPollResult> longPollResultCaptor = ArgumentCaptor.forClass(LongPollResult.class);
238 verify(longPollHandler).accept(longPollResultCaptor.capture());
239 LongPollResult longPollResult = longPollResultCaptor.getValue();
240 assertEquals(1, longPollResult.result.size());
241 assertEquals(longPollResult.result.get(0).getClass(), DeviceServiceData.class);
242 DeviceServiceData longPollResultItem = (DeviceServiceData) longPollResult.result.get(0);
243 assertEquals("hdm:HomeMaticIP:3014F711A0001916D859A8A9", longPollResultItem.deviceId);
244 assertEquals("/devices/hdm:HomeMaticIP:3014F711A0001916D859A8A9/services/PowerSwitch", longPollResultItem.path);
245 assertEquals("PowerSwitch", longPollResultItem.id);
246 JsonObject stateObject = (JsonObject) longPollResultItem.state;
247 assertNotNull(stateObject);
248 assertEquals("ON", stateObject.get("switchState").getAsString());
252 void startLongPolling_receiveScenario()
253 throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
254 // when(httpClient.getBoschSmartHomeUrl(anyString())).thenCallRealMethod();
255 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
257 Request subscribeRequest = mock(Request.class);
258 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
259 argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
260 SubscribeResult subscribeResult = new SubscribeResult();
261 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
263 Request longPollRequest = mock(Request.class);
264 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
265 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
267 fixture.start(httpClient);
269 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
270 verify(longPollRequest).send(completeListener.capture());
272 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
274 String longPollResultJSON = "{\"result\":[{\"@type\": \"scenarioTriggered\",\"name\": \"My scenario\",\"id\": \"509bd737-eed0-40b7-8caa-e8686a714399\",\"lastTimeTriggered\": \"1693758693032\"}],\"jsonrpc\":\"2.0\"}\n";
275 Response response = mock(Response.class);
276 bufferingResponseListener.onContent(response,
277 ByteBuffer.wrap(longPollResultJSON.getBytes(StandardCharsets.UTF_8)));
279 Result result = mock(Result.class);
280 bufferingResponseListener.onComplete(result);
282 ArgumentCaptor<LongPollResult> longPollResultCaptor = ArgumentCaptor.forClass(LongPollResult.class);
283 verify(longPollHandler).accept(longPollResultCaptor.capture());
284 LongPollResult longPollResult = longPollResultCaptor.getValue();
285 assertEquals(1, longPollResult.result.size());
286 assertEquals(longPollResult.result.get(0).getClass(), Scenario.class);
287 Scenario longPollResultItem = (Scenario) longPollResult.result.get(0);
288 assertEquals("509bd737-eed0-40b7-8caa-e8686a714399", longPollResultItem.id);
289 assertEquals("My scenario", longPollResultItem.name);
290 assertEquals("1693758693032", longPollResultItem.lastTimeTriggered);
294 void startSubscriptionFailure()
295 throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
296 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any()))
297 .thenThrow(new ExecutionException("Subscription failed.", null));
299 LongPollingFailedException e = assertThrows(LongPollingFailedException.class, () -> fixture.start(httpClient));
300 assertTrue(e.getMessage().contains("Subscription failed."));
304 void startLongPollFailure() throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
305 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
307 Request request = mock(Request.class);
308 when(httpClient.createRequest(anyString(), same(HttpMethod.POST), any(JsonRpcRequest.class)))
309 .thenReturn(request);
310 SubscribeResult subscribeResult = new SubscribeResult();
311 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
313 Request longPollRequest = mock(Request.class);
314 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
315 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
317 fixture.start(httpClient);
319 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
320 verify(longPollRequest).send(completeListener.capture());
322 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
324 Result result = mock(Result.class);
325 ExecutionException exception = new ExecutionException("test exception", null);
326 when(result.getFailure()).thenReturn(exception);
327 bufferingResponseListener.onComplete(result);
329 ArgumentCaptor<Throwable> throwableCaptor = ArgumentCaptor.forClass(Throwable.class);
330 verify(failureHandler).accept(throwableCaptor.capture());
331 Throwable t = throwableCaptor.getValue();
332 assertEquals("Unexpected exception during long polling request", t.getMessage());
333 assertSame(exception, t.getCause());
337 void startSubscriptionInvalid()
338 throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
339 when(httpClient.getBoschShcUrl(anyString())).thenCallRealMethod();
341 Request subscribeRequest = mock(Request.class);
342 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
343 argThat((JsonRpcRequest r) -> "RE/subscribe".equals(r.method)))).thenReturn(subscribeRequest);
344 SubscribeResult subscribeResult = new SubscribeResult();
345 when(httpClient.sendRequest(any(), same(SubscribeResult.class), any(), any())).thenReturn(subscribeResult);
347 Request longPollRequest = mock(Request.class);
348 when(httpClient.createRequest(anyString(), same(HttpMethod.POST),
349 argThat((JsonRpcRequest r) -> "RE/longPoll".equals(r.method)))).thenReturn(longPollRequest);
351 fixture.start(httpClient);
353 ArgumentCaptor<CompleteListener> completeListener = ArgumentCaptor.forClass(CompleteListener.class);
354 verify(longPollRequest).send(completeListener.capture());
356 BufferingResponseListener bufferingResponseListener = (BufferingResponseListener) completeListener.getValue();
358 String longPollResultJSON = "{\"jsonrpc\":\"2.0\",\"error\": {\"code\":-32001,\"message\":\"No subscription with id: e8fei62b0-0\"}}\n";
359 Response response = mock(Response.class);
360 bufferingResponseListener.onContent(response,
361 ByteBuffer.wrap(longPollResultJSON.getBytes(StandardCharsets.UTF_8)));
363 Result result = mock(Result.class);
364 bufferingResponseListener.onComplete(result);