]> git.basschouten.com Git - openhab-addons.git/blob
cfc1df26d8b4c422002f3d596eb164f98d687f55
[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.homeassistant.internal.component;
14
15 import static org.hamcrest.CoreMatchers.instanceOf;
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.ArgumentMatchers.anyBoolean;
20 import static org.mockito.ArgumentMatchers.anyInt;
21 import static org.mockito.ArgumentMatchers.eq;
22 import static org.mockito.Mockito.doAnswer;
23 import static org.mockito.Mockito.never;
24 import static org.mockito.Mockito.spy;
25 import static org.mockito.Mockito.times;
26 import static org.mockito.Mockito.verify;
27 import static org.mockito.Mockito.when;
28
29 import java.nio.charset.StandardCharsets;
30 import java.util.List;
31 import java.util.Objects;
32 import java.util.Set;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.TimeUnit;
35
36 import org.eclipse.jdt.annotation.NonNull;
37 import org.eclipse.jdt.annotation.NonNullByDefault;
38 import org.eclipse.jdt.annotation.Nullable;
39 import org.junit.jupiter.api.AfterEach;
40 import org.junit.jupiter.api.BeforeEach;
41 import org.mockito.Mock;
42 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
43 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
44 import org.openhab.binding.mqtt.generic.values.Value;
45 import org.openhab.binding.mqtt.homeassistant.internal.AbstractHomeAssistantTests;
46 import org.openhab.binding.mqtt.homeassistant.internal.ComponentChannel;
47 import org.openhab.binding.mqtt.homeassistant.internal.HaID;
48 import org.openhab.binding.mqtt.homeassistant.internal.HandlerConfiguration;
49 import org.openhab.binding.mqtt.homeassistant.internal.config.dto.AbstractChannelConfiguration;
50 import org.openhab.binding.mqtt.homeassistant.internal.handler.HomeAssistantThingHandler;
51 import org.openhab.core.thing.Thing;
52 import org.openhab.core.thing.ThingStatusInfo;
53 import org.openhab.core.thing.binding.ThingHandlerCallback;
54 import org.openhab.core.types.State;
55
56 /**
57  * Abstract class for components tests.
58  *
59  * @author Anton Kharuzhy - Initial contribution
60  */
61 @SuppressWarnings({ "ConstantConditions" })
62 @NonNullByDefault
63 public abstract class AbstractComponentTests extends AbstractHomeAssistantTests {
64     private static final int SUBSCRIBE_TIMEOUT = 10000;
65     private static final int ATTRIBUTE_RECEIVE_TIMEOUT = 2000;
66
67     private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
68     private @NonNullByDefault({}) LatchThingHandler thingHandler;
69
70     @BeforeEach
71     public void setupThingHandler() {
72         final var config = haThing.getConfiguration();
73
74         config.put(HandlerConfiguration.PROPERTY_BASETOPIC, HandlerConfiguration.DEFAULT_BASETOPIC);
75         config.put(HandlerConfiguration.PROPERTY_TOPICS, getConfigTopics());
76
77         // Plumb thing status updates through
78         doAnswer(invocation -> {
79             ((Thing) invocation.getArgument(0)).setStatusInfo((ThingStatusInfo) invocation.getArgument(1));
80             return null;
81         }).when(callbackMock).statusUpdated(any(Thing.class), any(ThingStatusInfo.class));
82
83         when(callbackMock.getBridge(eq(BRIDGE_UID))).thenReturn(bridgeThing);
84
85         thingHandler = new LatchThingHandler(haThing, channelTypeProvider, transformationServiceProvider,
86                 SUBSCRIBE_TIMEOUT, ATTRIBUTE_RECEIVE_TIMEOUT);
87         thingHandler.setConnection(bridgeConnection);
88         thingHandler.setCallback(callbackMock);
89         thingHandler = spy(thingHandler);
90
91         thingHandler.initialize();
92     }
93
94     @AfterEach
95     public void disposeThingHandler() {
96         thingHandler.dispose();
97     }
98
99     /**
100      * {@link org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents} will wait a config on specified
101      * topics.
102      * Topics in config must be without prefix and suffix, they can be converted to full with method
103      * {@link #configTopicToMqtt(String)}
104      *
105      * @return config topics
106      */
107     protected abstract Set<String> getConfigTopics();
108
109     /**
110      * Process payload to discover and configure component. Topic should be added to {@link #getConfigTopics()}
111      *
112      * @param mqttTopic mqtt topic with configuration
113      * @param json configuration payload in Json
114      * @return discovered component
115      */
116     protected AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> discoverComponent(String mqttTopic,
117             String json) {
118         return discoverComponent(mqttTopic, json.getBytes(StandardCharsets.UTF_8));
119     }
120
121     /**
122      * Process payload to discover and configure component. Topic should be added to {@link #getConfigTopics()}
123      *
124      * @param mqttTopic mqtt topic with configuration
125      * @param jsonPayload configuration payload in Json
126      * @return discovered component
127      */
128     protected AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> discoverComponent(String mqttTopic,
129             byte[] jsonPayload) {
130         var latch = thingHandler.createWaitForComponentDiscoveredLatch(1);
131         assertThat(publishMessage(mqttTopic, jsonPayload), is(true));
132         try {
133             assert latch.await(1, TimeUnit.SECONDS);
134         } catch (InterruptedException e) {
135             assertThat(e.getMessage(), false);
136         }
137         return Objects.requireNonNull(thingHandler.getDiscoveredComponent());
138     }
139
140     /**
141      * Assert channel topics, label and value class
142      *
143      * @param component component
144      * @param channelId channel
145      * @param stateTopic state topic or empty string
146      * @param commandTopic command topic or empty string
147      * @param label label
148      * @param valueClass value class
149      */
150     protected static void assertChannel(AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> component,
151             String channelId, String stateTopic, String commandTopic, String label, Class<? extends Value> valueClass) {
152         var stateChannel = Objects.requireNonNull(component.getChannel(channelId));
153         assertChannel(stateChannel, stateTopic, commandTopic, label, valueClass);
154     }
155
156     /**
157      * Assert channel topics, label and value class
158      *
159      * @param stateChannel channel
160      * @param stateTopic state topic or empty string
161      * @param commandTopic command topic or empty string
162      * @param label label
163      * @param valueClass value class
164      */
165     protected static void assertChannel(ComponentChannel stateChannel, String stateTopic, String commandTopic,
166             String label, Class<? extends Value> valueClass) {
167         assertThat(stateChannel.getChannel().getLabel(), is(label));
168         assertThat(stateChannel.getState().getStateTopic(), is(stateTopic));
169         assertThat(stateChannel.getState().getCommandTopic(), is(commandTopic));
170         assertThat(stateChannel.getState().getCache(), is(instanceOf(valueClass)));
171     }
172
173     /**
174      * Assert channel state
175      *
176      * @param component component
177      * @param channelId channel
178      * @param state expected state
179      */
180     protected static void assertState(AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> component,
181             String channelId, State state) {
182         assertThat(component.getChannel(channelId).getState().getCache().getChannelState(), is(state));
183     }
184
185     /**
186      * Assert that given payload was published exact-once on given topic.
187      *
188      * @param mqttTopic Mqtt topic
189      * @param payload payload
190      */
191     protected void assertPublished(String mqttTopic, String payload) {
192         verify(bridgeConnection).publish(eq(mqttTopic), eq(payload.getBytes(StandardCharsets.UTF_8)), anyInt(),
193                 anyBoolean());
194     }
195
196     /**
197      * Assert that given payload was published N times on given topic.
198      *
199      * @param mqttTopic Mqtt topic
200      * @param payload payload
201      * @param t payload must be published N times on given topic
202      */
203     protected void assertPublished(String mqttTopic, String payload, int t) {
204         verify(bridgeConnection, times(t)).publish(eq(mqttTopic), eq(payload.getBytes(StandardCharsets.UTF_8)),
205                 anyInt(), anyBoolean());
206     }
207
208     /**
209      * Assert that given payload was not published on given topic.
210      *
211      * @param mqttTopic Mqtt topic
212      * @param payload payload
213      */
214     protected void assertNotPublished(String mqttTopic, String payload) {
215         verify(bridgeConnection, never()).publish(eq(mqttTopic), eq(payload.getBytes(StandardCharsets.UTF_8)), anyInt(),
216                 anyBoolean());
217     }
218
219     /**
220      * Publish payload to all subscribers on specified topic.
221      *
222      * @param mqttTopic Mqtt topic
223      * @param payload payload
224      * @return true when at least one subscriber found
225      */
226     protected boolean publishMessage(String mqttTopic, String payload) {
227         return publishMessage(mqttTopic, payload.getBytes(StandardCharsets.UTF_8));
228     }
229
230     /**
231      * Publish payload to all subscribers on specified topic.
232      *
233      * @param mqttTopic Mqtt topic
234      * @param payload payload
235      * @return true when at least one subscriber found
236      */
237     protected boolean publishMessage(String mqttTopic, byte[] payload) {
238         final var topicSubscribers = subscriptions.get(mqttTopic);
239
240         if (topicSubscribers != null && !topicSubscribers.isEmpty()) {
241             topicSubscribers.forEach(mqttMessageSubscriber -> mqttMessageSubscriber.processMessage(mqttTopic, payload));
242             return true;
243         }
244         return false;
245     }
246
247     protected static class LatchThingHandler extends HomeAssistantThingHandler {
248         private @Nullable CountDownLatch latch;
249         private @Nullable AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> discoveredComponent;
250
251         public LatchThingHandler(Thing thing, MqttChannelTypeProvider channelTypeProvider,
252                 TransformationServiceProvider transformationServiceProvider, int subscribeTimeout,
253                 int attributeReceiveTimeout) {
254             super(thing, channelTypeProvider, transformationServiceProvider, subscribeTimeout, attributeReceiveTimeout);
255         }
256
257         @Override
258         public void componentDiscovered(HaID homeAssistantTopicID, AbstractComponent<@NonNull ?> component) {
259             accept(List.of(component));
260             discoveredComponent = component;
261             if (latch != null) {
262                 latch.countDown();
263             }
264         }
265
266         public CountDownLatch createWaitForComponentDiscoveredLatch(int count) {
267             final var newLatch = new CountDownLatch(count);
268             latch = newLatch;
269             return newLatch;
270         }
271
272         public @Nullable AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> getDiscoveredComponent() {
273             return discoveredComponent;
274         }
275     }
276 }