2 * Copyright (c) 2010-2022 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.mqtt.homeassistant.internal.component;
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;
29 import java.nio.charset.StandardCharsets;
30 import java.util.List;
31 import java.util.Objects;
33 import java.util.concurrent.CountDownLatch;
34 import java.util.concurrent.TimeUnit;
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;
57 * Abstract class for components tests.
59 * @author Anton Kharuzhy - Initial contribution
61 @SuppressWarnings({ "ConstantConditions" })
63 public abstract class AbstractComponentTests extends AbstractHomeAssistantTests {
64 private static final int SUBSCRIBE_TIMEOUT = 10000;
65 private static final int ATTRIBUTE_RECEIVE_TIMEOUT = 2000;
67 private @Mock @NonNullByDefault({}) ThingHandlerCallback callbackMock;
68 private @NonNullByDefault({}) LatchThingHandler thingHandler;
71 public void setupThingHandler() {
72 final var config = haThing.getConfiguration();
74 config.put(HandlerConfiguration.PROPERTY_BASETOPIC, HandlerConfiguration.DEFAULT_BASETOPIC);
75 config.put(HandlerConfiguration.PROPERTY_TOPICS, getConfigTopics());
77 // Plumb thing status updates through
78 doAnswer(invocation -> {
79 ((Thing) invocation.getArgument(0)).setStatusInfo((ThingStatusInfo) invocation.getArgument(1));
81 }).when(callbackMock).statusUpdated(any(Thing.class), any(ThingStatusInfo.class));
83 when(callbackMock.getBridge(eq(BRIDGE_UID))).thenReturn(bridgeThing);
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);
91 thingHandler.initialize();
95 public void disposeThingHandler() {
96 thingHandler.dispose();
100 * {@link org.openhab.binding.mqtt.homeassistant.internal.DiscoverComponents} will wait a config on specified
102 * Topics in config must be without prefix and suffix, they can be converted to full with method
103 * {@link #configTopicToMqtt(String)}
105 * @return config topics
107 protected abstract Set<String> getConfigTopics();
110 * Process payload to discover and configure component. Topic should be added to {@link #getConfigTopics()}
112 * @param mqttTopic mqtt topic with configuration
113 * @param json configuration payload in Json
114 * @return discovered component
116 protected AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> discoverComponent(String mqttTopic,
118 return discoverComponent(mqttTopic, json.getBytes(StandardCharsets.UTF_8));
122 * Process payload to discover and configure component. Topic should be added to {@link #getConfigTopics()}
124 * @param mqttTopic mqtt topic with configuration
125 * @param jsonPayload configuration payload in Json
126 * @return discovered component
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));
133 assert latch.await(1, TimeUnit.SECONDS);
134 } catch (InterruptedException e) {
135 assertThat(e.getMessage(), false);
137 return Objects.requireNonNull(thingHandler.getDiscoveredComponent());
141 * Assert channel topics, label and value class
143 * @param component component
144 * @param channelId channel
145 * @param stateTopic state topic or empty string
146 * @param commandTopic command topic or empty string
148 * @param valueClass value class
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);
157 * Assert channel topics, label and value class
159 * @param stateChannel channel
160 * @param stateTopic state topic or empty string
161 * @param commandTopic command topic or empty string
163 * @param valueClass value class
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)));
174 * Assert channel state
176 * @param component component
177 * @param channelId channel
178 * @param state expected state
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));
186 * Assert that given payload was published exact-once on given topic.
188 * @param mqttTopic Mqtt topic
189 * @param payload payload
191 protected void assertPublished(String mqttTopic, String payload) {
192 verify(bridgeConnection).publish(eq(mqttTopic), eq(payload.getBytes(StandardCharsets.UTF_8)), anyInt(),
197 * Assert that given payload was published N times on given topic.
199 * @param mqttTopic Mqtt topic
200 * @param payload payload
201 * @param t payload must be published N times on given topic
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());
209 * Assert that given payload was not published on given topic.
211 * @param mqttTopic Mqtt topic
212 * @param payload payload
214 protected void assertNotPublished(String mqttTopic, String payload) {
215 verify(bridgeConnection, never()).publish(eq(mqttTopic), eq(payload.getBytes(StandardCharsets.UTF_8)), anyInt(),
220 * Publish payload to all subscribers on specified topic.
222 * @param mqttTopic Mqtt topic
223 * @param payload payload
224 * @return true when at least one subscriber found
226 protected boolean publishMessage(String mqttTopic, String payload) {
227 return publishMessage(mqttTopic, payload.getBytes(StandardCharsets.UTF_8));
231 * Publish payload to all subscribers on specified topic.
233 * @param mqttTopic Mqtt topic
234 * @param payload payload
235 * @return true when at least one subscriber found
237 protected boolean publishMessage(String mqttTopic, byte[] payload) {
238 final var topicSubscribers = subscriptions.get(mqttTopic);
240 if (topicSubscribers != null && !topicSubscribers.isEmpty()) {
241 topicSubscribers.forEach(mqttMessageSubscriber -> mqttMessageSubscriber.processMessage(mqttTopic, payload));
247 protected static class LatchThingHandler extends HomeAssistantThingHandler {
248 private @Nullable CountDownLatch latch;
249 private @Nullable AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> discoveredComponent;
251 public LatchThingHandler(Thing thing, MqttChannelTypeProvider channelTypeProvider,
252 TransformationServiceProvider transformationServiceProvider, int subscribeTimeout,
253 int attributeReceiveTimeout) {
254 super(thing, channelTypeProvider, transformationServiceProvider, subscribeTimeout, attributeReceiveTimeout);
258 public void componentDiscovered(HaID homeAssistantTopicID, AbstractComponent<@NonNull ?> component) {
259 accept(List.of(component));
260 discoveredComponent = component;
266 public CountDownLatch createWaitForComponentDiscoveredLatch(int count) {
267 final var newLatch = new CountDownLatch(count);
272 public @Nullable AbstractComponent<@NonNull ? extends AbstractChannelConfiguration> getDiscoveredComponent() {
273 return discoveredComponent;