2 * Copyright (c) 2010-2024 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;
15 import static org.mockito.ArgumentMatchers.*;
16 import static org.mockito.Mockito.*;
18 import java.io.IOException;
19 import java.net.URISyntaxException;
20 import java.nio.file.Files;
21 import java.nio.file.Path;
22 import java.nio.file.Paths;
23 import java.util.Objects;
25 import java.util.UUID;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.junit.jupiter.api.Assertions;
32 import org.junit.jupiter.api.BeforeEach;
33 import org.junit.jupiter.api.extension.ExtendWith;
34 import org.mockito.Mock;
35 import org.mockito.Mockito;
36 import org.mockito.junit.jupiter.MockitoExtension;
37 import org.mockito.junit.jupiter.MockitoSettings;
38 import org.mockito.quality.Strictness;
39 import org.openhab.binding.mqtt.generic.MqttChannelStateDescriptionProvider;
40 import org.openhab.binding.mqtt.generic.MqttChannelTypeProvider;
41 import org.openhab.binding.mqtt.handler.BrokerHandler;
42 import org.openhab.binding.mqtt.homeassistant.generic.internal.MqttBindingConstants;
43 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
44 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
45 import org.openhab.core.test.java.JavaTest;
46 import org.openhab.core.test.storage.VolatileStorageService;
47 import org.openhab.core.thing.Bridge;
48 import org.openhab.core.thing.Thing;
49 import org.openhab.core.thing.ThingStatus;
50 import org.openhab.core.thing.ThingStatusDetail;
51 import org.openhab.core.thing.ThingStatusInfo;
52 import org.openhab.core.thing.ThingTypeUID;
53 import org.openhab.core.thing.ThingUID;
54 import org.openhab.core.thing.binding.builder.BridgeBuilder;
55 import org.openhab.core.thing.binding.builder.ThingBuilder;
56 import org.openhab.core.thing.type.ChannelTypeRegistry;
57 import org.openhab.core.thing.type.ThingType;
58 import org.openhab.core.thing.type.ThingTypeBuilder;
59 import org.openhab.core.thing.type.ThingTypeRegistry;
60 import org.openhab.core.transform.TransformationHelper;
61 import org.openhab.core.transform.TransformationService;
62 import org.openhab.transform.jinja.internal.JinjaTransformationService;
63 import org.openhab.transform.jinja.internal.profiles.JinjaTransformationProfile;
64 import org.osgi.framework.BundleContext;
65 import org.osgi.framework.ServiceReference;
68 * Abstract class for HomeAssistant unit tests.
70 * @author Anton Kharuzhy - Initial contribution
72 @ExtendWith(MockitoExtension.class)
73 @MockitoSettings(strictness = Strictness.LENIENT)
75 public abstract class AbstractHomeAssistantTests extends JavaTest {
76 public static final String BINDING_ID = "mqtt";
78 public static final String BRIDGE_TYPE_ID = "broker";
79 public static final String BRIDGE_TYPE_LABEL = "MQTT Broker";
80 public static final ThingTypeUID BRIDGE_TYPE_UID = new ThingTypeUID(BINDING_ID, BRIDGE_TYPE_ID);
81 public static final String BRIDGE_ID = UUID.randomUUID().toString();
82 public static final ThingUID BRIDGE_UID = new ThingUID(BRIDGE_TYPE_UID, BRIDGE_ID);
84 public static final String HA_TYPE_LABEL = "Home Assistant Thing";
85 public static final ThingTypeUID HA_TYPE_UID = new ThingTypeUID(BINDING_ID, "homeassistant_dynamic_type");
86 public static final String HA_ID = UUID.randomUUID().toString();
87 public static final ThingUID HA_UID = new ThingUID(MqttBindingConstants.HOMEASSISTANT_MQTT_THING, HA_ID);
88 public static final ThingType HA_THING_TYPE = ThingTypeBuilder
89 .instance(MqttBindingConstants.HOMEASSISTANT_MQTT_THING, HA_TYPE_LABEL).build();
91 protected @Mock @NonNullByDefault({}) MqttBrokerConnection bridgeConnection;
92 protected @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistry;
94 protected @NonNullByDefault({}) MqttChannelTypeProvider channelTypeProvider;
95 protected @NonNullByDefault({}) MqttChannelStateDescriptionProvider stateDescriptionProvider;
96 protected @NonNullByDefault({}) ChannelTypeRegistry channelTypeRegistry;
98 protected final Bridge bridgeThing = BridgeBuilder.create(BRIDGE_TYPE_UID, BRIDGE_UID).build();
99 protected final BrokerHandler bridgeHandler = spy(new BrokerHandler(bridgeThing));
100 protected final Thing haThing = ThingBuilder.create(HA_TYPE_UID, HA_UID).withBridge(BRIDGE_UID).build();
101 protected final ConcurrentMap<String, Set<MqttMessageSubscriber>> subscriptions = new ConcurrentHashMap<>();
103 private @Mock @NonNullByDefault({}) TransformationService transformationService1Mock;
105 private @Mock @NonNullByDefault({}) BundleContext bundleContextMock;
106 private @Mock @NonNullByDefault({}) ServiceReference<TransformationService> serviceRefMock;
108 private @NonNullByDefault({}) TransformationHelper transformationHelper;
110 private final JinjaTransformationService jinjaTransformationService = new JinjaTransformationService();
113 public void beforeEachAbstractHomeAssistantTests() {
114 Mockito.when(serviceRefMock.getProperty(any())).thenReturn(JinjaTransformationProfile.PROFILE_TYPE_UID.getId());
116 Mockito.when(bundleContextMock.getService(serviceRefMock)).thenReturn(jinjaTransformationService);
118 transformationHelper = new TransformationHelper(bundleContextMock);
119 transformationHelper.setTransformationService(serviceRefMock);
121 when(thingTypeRegistry.getThingType(BRIDGE_TYPE_UID))
122 .thenReturn(ThingTypeBuilder.instance(BRIDGE_TYPE_UID, BRIDGE_TYPE_LABEL).build());
123 when(thingTypeRegistry.getThingType(MqttBindingConstants.HOMEASSISTANT_MQTT_THING)).thenReturn(HA_THING_TYPE);
125 channelTypeProvider = spy(new MqttChannelTypeProvider(thingTypeRegistry, new VolatileStorageService()));
126 stateDescriptionProvider = spy(new MqttChannelStateDescriptionProvider());
127 channelTypeRegistry = spy(new ChannelTypeRegistry());
131 // Return the mocked connection object if the bridge handler is asked for it
132 when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(bridgeConnection));
134 bridgeThing.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.ONLINE.NONE, ""));
135 bridgeThing.setHandler(bridgeHandler);
137 haThing.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.ONLINE.NONE, ""));
140 protected void setupConnection() {
141 doAnswer(invocation -> {
142 final var topic = (String) invocation.getArgument(0);
143 final var subscriber = (MqttMessageSubscriber) invocation.getArgument(1);
145 subscriptions.putIfAbsent(topic, ConcurrentHashMap.newKeySet());
146 Set<MqttMessageSubscriber> subscribers = subscriptions.get(topic);
147 Objects.requireNonNull(subscribers); // Invariant, thanks to putIfAbsent above. To make compiler happy
148 subscribers.add(subscriber);
149 return CompletableFuture.completedFuture(true);
150 }).when(bridgeConnection).subscribe(any(), any());
152 doAnswer(invocation -> {
153 final var topic = (String) invocation.getArgument(0);
154 final var subscriber = (MqttMessageSubscriber) invocation.getArgument(1);
155 final var topicSubscriptions = subscriptions.get(topic);
157 if (topicSubscriptions != null) {
158 topicSubscriptions.remove(subscriber);
160 return CompletableFuture.completedFuture(true);
161 }).when(bridgeConnection).unsubscribe(any(), any());
163 doAnswer(invocation -> {
164 subscriptions.clear();
165 return CompletableFuture.completedFuture(true);
166 }).when(bridgeConnection).unsubscribeAll();
168 doReturn(CompletableFuture.completedFuture(true)).when(bridgeConnection).publish(any(), any(), anyInt(),
173 * @param relativePath path from src/test/java/org/openhab/binding/mqtt/homeassistant/internal
176 @SuppressWarnings("null")
177 protected Path getResourcePath(String relativePath) {
179 return Paths.get(AbstractHomeAssistantTests.class.getResource(relativePath).toURI());
180 } catch (URISyntaxException e) {
183 throw new IllegalArgumentException();
186 protected String getResourceAsString(String relativePath) {
188 return Files.readString(getResourcePath(relativePath));
189 } catch (IOException e) {
192 throw new IllegalArgumentException();
195 protected byte[] getResourceAsByteArray(String relativePath) {
197 return Files.readAllBytes(getResourcePath(relativePath));
198 } catch (IOException e) {
201 throw new IllegalArgumentException();
204 protected static String configTopicToMqtt(String configTopic) {
205 return HandlerConfiguration.DEFAULT_BASETOPIC + "/" + configTopic + "/config";