]> git.basschouten.com Git - openhab-addons.git/blob
82a16140bd8235161378bae5a1c7b86cb6f178d9
[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.mqtt.homie.internal.handler;
14
15 import static org.eclipse.jdt.annotation.Checks.requireNonNull;
16 import static org.hamcrest.CoreMatchers.is;
17 import static org.hamcrest.MatcherAssert.assertThat;
18 import static org.junit.jupiter.api.Assertions.*;
19 import static org.mockito.ArgumentMatchers.*;
20 import static org.mockito.Mockito.*;
21 import static org.openhab.binding.mqtt.homie.internal.handler.ThingChannelConstants.TEST_HOMIE_THING;
22
23 import java.lang.reflect.Field;
24 import java.util.ArrayList;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.concurrent.CompletableFuture;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ScheduledExecutorService;
30 import java.util.concurrent.ScheduledFuture;
31 import java.util.concurrent.TimeUnit;
32
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.junit.jupiter.api.BeforeEach;
36 import org.junit.jupiter.api.Test;
37 import org.junit.jupiter.api.extension.ExtendWith;
38 import org.mockito.Mock;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.mockito.junit.jupiter.MockitoExtension;
41 import org.mockito.junit.jupiter.MockitoSettings;
42 import org.mockito.quality.Strictness;
43 import org.openhab.binding.mqtt.generic.ChannelState;
44 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
45 import org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass;
46 import org.openhab.binding.mqtt.generic.mapping.SubscribeFieldToMQTTtopic;
47 import org.openhab.binding.mqtt.generic.tools.ChildMap;
48 import org.openhab.binding.mqtt.generic.tools.DelayedBatchProcessing;
49 import org.openhab.binding.mqtt.generic.values.Value;
50 import org.openhab.binding.mqtt.handler.AbstractBrokerHandler;
51 import org.openhab.binding.mqtt.homie.ChannelStateHelper;
52 import org.openhab.binding.mqtt.homie.ThingHandlerHelper;
53 import org.openhab.binding.mqtt.homie.generic.internal.MqttBindingConstants;
54 import org.openhab.binding.mqtt.homie.internal.homie300.Device;
55 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceAttributes;
56 import org.openhab.binding.mqtt.homie.internal.homie300.DeviceAttributes.ReadyState;
57 import org.openhab.binding.mqtt.homie.internal.homie300.Node;
58 import org.openhab.binding.mqtt.homie.internal.homie300.NodeAttributes;
59 import org.openhab.binding.mqtt.homie.internal.homie300.Property;
60 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyAttributes;
61 import org.openhab.binding.mqtt.homie.internal.homie300.PropertyAttributes.DataTypeEnum;
62 import org.openhab.core.config.core.Configuration;
63 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
64 import org.openhab.core.library.types.StringType;
65 import org.openhab.core.thing.Channel;
66 import org.openhab.core.thing.Thing;
67 import org.openhab.core.thing.ThingStatus;
68 import org.openhab.core.thing.ThingStatusDetail;
69 import org.openhab.core.thing.ThingStatusInfo;
70 import org.openhab.core.thing.binding.ThingHandlerCallback;
71 import org.openhab.core.thing.binding.builder.ThingBuilder;
72 import org.openhab.core.thing.type.ChannelKind;
73 import org.openhab.core.thing.type.ThingTypeRegistry;
74 import org.openhab.core.types.Command;
75 import org.openhab.core.types.RefreshType;
76 import org.openhab.core.types.TypeParser;
77
78 /**
79  * Tests cases for {@link HomieThingHandler}.
80  *
81  * @author David Graeff - Initial contribution
82  */
83 @ExtendWith(MockitoExtension.class)
84 @MockitoSettings(strictness = Strictness.WARN)
85 public class HomieThingHandlerTests {
86
87     private Thing thing;
88
89     private @Mock AbstractBrokerHandler bridgeHandler;
90     private @Mock ThingHandlerCallback callback;
91     private @Mock MqttBrokerConnection connection;
92     private @Mock ScheduledExecutorService scheduler;
93     private @Mock ScheduledFuture<?> scheduledFuture;
94     private @Mock ThingTypeRegistry thingTypeRegistry;
95
96     private HomieThingHandler thingHandler;
97
98     private final MqttChannelTypeProvider channelTypeProvider = new MqttChannelTypeProvider(thingTypeRegistry);
99
100     private final String deviceID = ThingChannelConstants.TEST_HOMIE_THING.getId();
101     private final String deviceTopic = "homie/" + deviceID;
102
103     // A completed future is returned for a subscribe call to the attributes
104     private CompletableFuture<@Nullable Void> future = CompletableFuture.completedFuture(null);
105
106     @BeforeEach
107     public void setUp() {
108         final ThingStatusInfo thingStatus = new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null);
109
110         final Configuration config = new Configuration();
111         config.put("basetopic", "homie");
112         config.put("deviceid", deviceID);
113
114         thing = ThingBuilder.create(MqttBindingConstants.HOMIE300_MQTT_THING, TEST_HOMIE_THING.getId())
115                 .withConfiguration(config).build();
116         thing.setStatusInfo(thingStatus);
117
118         // Return the mocked connection object if the bridge handler is asked for it
119         when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(connection));
120
121         doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
122         doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
123         doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribeAll();
124         doReturn(CompletableFuture.completedFuture(true)).when(connection).publish(any(), any(), anyInt(),
125                 anyBoolean());
126
127         doReturn(false).when(scheduledFuture).isDone();
128         doReturn(scheduledFuture).when(scheduler).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class));
129
130         final HomieThingHandler handler = new HomieThingHandler(thing, channelTypeProvider, 1000, 30, 5);
131         thingHandler = spy(handler);
132         thingHandler.setCallback(callback);
133         final Device device = new Device(thing.getUID(), thingHandler, spy(new DeviceAttributes()),
134                 spy(new ChildMap<>()));
135         thingHandler.setInternalObjects(spy(device), spy(new DelayedBatchProcessing<>(500, thingHandler, scheduler)));
136
137         // Return the bridge handler if the thing handler asks for it
138         doReturn(bridgeHandler).when(thingHandler).getBridgeHandler();
139
140         // We are by default online
141         doReturn(thingStatus).when(thingHandler).getBridgeStatus();
142     }
143
144     @Test
145     public void initialize() {
146         assertThat(thingHandler.device.isInitialized(), is(false));
147         // // A completed future is returned for a subscribe call to the attributes
148         doReturn(future).when(thingHandler.device.attributes).subscribeAndReceive(any(), any(), anyString(), any(),
149                 anyInt());
150         doReturn(future).when(thingHandler.device.attributes).unsubscribe();
151         // Prevent a call to accept, that would update our thing.
152         doNothing().when(thingHandler).accept(any());
153         // Pretend that a device state change arrived.
154         thingHandler.device.attributes.state = ReadyState.ready;
155
156         verify(callback, times(0)).statusUpdated(eq(thing), any());
157
158         thingHandler.initialize();
159
160         // Expect a call to the bridge status changed, the start, the propertiesChanged method
161         verify(thingHandler).bridgeStatusChanged(any());
162         verify(thingHandler).start(any());
163         verify(thingHandler).readyStateChanged(any());
164         verify(thingHandler.device.attributes).subscribeAndReceive(any(), any(),
165                 argThat(arg -> deviceTopic.equals(arg)), any(), anyInt());
166
167         assertThat(thingHandler.device.isInitialized(), is(true));
168
169         verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.ONLINE)
170                 && arg.getStatusDetail().equals(ThingStatusDetail.NONE)));
171     }
172
173     @Test
174     public void initializeGeneralTimeout() throws InterruptedException {
175         // A non completed future is returned for a subscribe call to the attributes
176         doReturn(future).when(thingHandler.device.attributes).subscribeAndReceive(any(), any(), anyString(), any(),
177                 anyInt());
178         doReturn(future).when(thingHandler.device.attributes).unsubscribe();
179
180         // Prevent a call to accept, that would update our thing.
181         doNothing().when(thingHandler).accept(any());
182
183         thingHandler.initialize();
184
185         verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.OFFLINE)
186                 && arg.getStatusDetail().equals(ThingStatusDetail.COMMUNICATION_ERROR)));
187     }
188
189     @Test
190     public void initializeNoStateReceived() throws InterruptedException {
191         // A completed future is returned for a subscribe call to the attributes
192         doReturn(future).when(thingHandler.device.attributes).subscribeAndReceive(any(), any(), anyString(), any(),
193                 anyInt());
194         doReturn(future).when(thingHandler.device.attributes).unsubscribe();
195
196         // Prevent a call to accept, that would update our thing.
197         doNothing().when(thingHandler).accept(any());
198
199         thingHandler.initialize();
200         assertThat(thingHandler.device.isInitialized(), is(true));
201
202         verify(callback).statusUpdated(eq(thing), argThat((arg) -> arg.getStatus().equals(ThingStatus.OFFLINE)
203                 && arg.getStatusDetail().equals(ThingStatusDetail.GONE)));
204     }
205
206     @SuppressWarnings("null")
207     @Test
208     public void handleCommandRefresh() {
209         // Create mocked homie device tree with one node and one read-only property
210         Node node = thingHandler.device.createNode("node", spy(new NodeAttributes()));
211         doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
212         doReturn(future).when(node.attributes).unsubscribe();
213         node.attributes.name = "testnode";
214
215         Property property = node.createProperty("property", spy(new PropertyAttributes()));
216         doReturn(future).when(property.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
217         doReturn(future).when(property.attributes).unsubscribe();
218         property.attributes.name = "testprop";
219         property.attributes.datatype = DataTypeEnum.string_;
220         property.attributes.settable = false;
221         property.attributesReceived();
222         node.properties.put(property.propertyID, property);
223         thingHandler.device.nodes.put(node.nodeID, node);
224
225         ThingHandlerHelper.setConnection(thingHandler, connection);
226         // we need to set a channel value first, undefined values ignored on REFRESH
227         property.getChannelState().getCache().update(new StringType("testString"));
228
229         thingHandler.handleCommand(property.channelUID, RefreshType.REFRESH);
230         verify(callback).stateUpdated(argThat(arg -> property.channelUID.equals(arg)),
231                 argThat(arg -> property.getChannelState().getCache().getChannelState().equals(arg)));
232     }
233
234     @SuppressWarnings("null")
235     @Test
236     public void handleCommandUpdate() {
237         // Create mocked homie device tree with one node and one writable property
238         Node node = thingHandler.device.createNode("node", spy(new NodeAttributes()));
239         doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
240         doReturn(future).when(node.attributes).unsubscribe();
241         node.attributes.name = "testnode";
242
243         Property property = node.createProperty("property", spy(new PropertyAttributes()));
244         doReturn(future).when(property.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
245         doReturn(future).when(property.attributes).unsubscribe();
246         property.attributes.name = "testprop";
247         property.attributes.datatype = DataTypeEnum.string_;
248         property.attributes.settable = true;
249         property.attributesReceived();
250         node.properties.put(property.propertyID, property);
251         thingHandler.device.nodes.put(node.nodeID, node);
252
253         ChannelState channelState = requireNonNull(property.getChannelState());
254         assertNotNull(channelState);
255         ChannelStateHelper.setConnection(channelState, connection);// Pretend we called start()
256         ThingHandlerHelper.setConnection(thingHandler, connection);
257
258         StringType updateValue = new StringType("UPDATE");
259         thingHandler.handleCommand(property.channelUID, updateValue);
260
261         assertThat(property.getChannelState().getCache().getChannelState().toString(), is("UPDATE"));
262         verify(connection, times(1)).publish(any(), any(), anyInt(), anyBoolean());
263
264         // Check non writable property
265         property.attributes.settable = false;
266         property.attributesReceived();
267         // Assign old value
268         Value value = property.getChannelState().getCache();
269         Command command = TypeParser.parseCommand(value.getSupportedCommandTypes(), "OLDVALUE");
270         if (command != null) {
271             property.getChannelState().getCache().update(command);
272             // Try to update with new value
273             updateValue = new StringType("SOMETHINGNEW");
274             thingHandler.handleCommand(property.channelUID, updateValue);
275             // Expect old value and no MQTT publish
276             assertThat(property.getChannelState().getCache().getChannelState().toString(), is("OLDVALUE"));
277             verify(connection, times(1)).publish(any(), any(), anyInt(), anyBoolean());
278         }
279     }
280
281     public Object createSubscriberAnswer(InvocationOnMock invocation) {
282         final AbstractMqttAttributeClass attributes = (AbstractMqttAttributeClass) invocation.getMock();
283         final ScheduledExecutorService scheduler = (ScheduledExecutorService) invocation.getArguments()[0];
284         final Field field = (Field) invocation.getArguments()[1];
285         final String topic = (String) invocation.getArguments()[2];
286         final boolean mandatory = (boolean) invocation.getArguments()[3];
287         final SubscribeFieldToMQTTtopic s = spy(
288                 new SubscribeFieldToMQTTtopic(scheduler, field, attributes, topic, mandatory));
289         doReturn(CompletableFuture.completedFuture(true)).when(s).subscribeAndReceive(any(), anyInt());
290         return s;
291     }
292
293     public Property createSpyProperty(String propertyID, Node node) {
294         // Create a property with the same ID and insert it instead
295         Property property = spy(node.createProperty(propertyID, spy(new PropertyAttributes())));
296         doAnswer(this::createSubscriberAnswer).when(property.attributes).createSubscriber(any(), any(), any(),
297                 anyBoolean());
298         property.attributes.name = "testprop";
299         property.attributes.datatype = DataTypeEnum.string_;
300
301         return property;
302     }
303
304     public Node createSpyNode(String propertyID, Device device) {
305         // Create the node
306         Node node = spy(device.createNode("node", spy(new NodeAttributes())));
307         doReturn(future).when(node.attributes).subscribeAndReceive(any(), any(), anyString(), any(), anyInt());
308         doReturn(future).when(node.attributes).unsubscribe();
309         node.attributes.name = "testnode";
310         node.attributes.properties = new String[] { "property" };
311         doAnswer(this::createSubscriberAnswer).when(node.attributes).createSubscriber(any(), any(), any(),
312                 anyBoolean());
313
314         // Intercept creating a property in the next call and inject a spy'ed property.
315         doAnswer(i -> createSpyProperty("property", node)).when(node).createProperty(any());
316
317         return node;
318     }
319
320     @Test
321     public void propertiesChanged() throws InterruptedException, ExecutionException {
322         thingHandler.device.initialize("homie", "device", new ArrayList<>());
323         ThingHandlerHelper.setConnection(thingHandler, connection);
324
325         // Create mocked homie device tree with one node and one property
326         doAnswer(this::createSubscriberAnswer).when(thingHandler.device.attributes).createSubscriber(any(), any(),
327                 any(), anyBoolean());
328
329         thingHandler.device.attributes.state = ReadyState.ready;
330         thingHandler.device.attributes.name = "device";
331         thingHandler.device.attributes.homie = "3.0";
332         thingHandler.device.attributes.nodes = new String[] { "node" };
333
334         // Intercept creating a node in initialize()->start() and inject a spy'ed node.
335         doAnswer(i -> createSpyNode("node", thingHandler.device)).when(thingHandler.device).createNode(any());
336
337         verify(thingHandler, times(0)).nodeAddedOrChanged(any());
338         verify(thingHandler, times(0)).propertyAddedOrChanged(any());
339
340         thingHandler.initialize();
341
342         assertThat(thingHandler.device.isInitialized(), is(true));
343
344         verify(thingHandler).propertyAddedOrChanged(any());
345         verify(thingHandler).nodeAddedOrChanged(any());
346
347         verify(thingHandler.device).subscribe(any(), any(), anyInt());
348         verify(thingHandler.device).attributesReceived(any(), any(), anyInt());
349
350         assertNotNull(thingHandler.device.nodes.get("node").properties.get("property"));
351
352         assertTrue(thingHandler.delayedProcessing.isArmed());
353
354         // Simulate waiting for the delayed processor
355         thingHandler.delayedProcessing.forceProcessNow();
356
357         // Called for the updated property + for the new channels
358         verify(callback, atLeast(2)).thingUpdated(any());
359
360         final List<@NonNull Channel> channels = thingHandler.getThing().getChannels();
361         assertThat(channels.size(), is(1));
362         assertThat(channels.get(0).getLabel(), is("testprop"));
363         assertThat(channels.get(0).getKind(), is(ChannelKind.STATE));
364
365         final Map<@NonNull String, @NonNull String> properties = thingHandler.getThing().getProperties();
366         assertThat(properties.get(MqttBindingConstants.HOMIE_PROPERTY_VERSION), is("3.0"));
367         assertThat(properties.size(), is(1));
368     }
369 }