]> git.basschouten.com Git - openhab-addons.git/blob
3e3de4afbffd3369b21f5720e328721261b24c5d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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;
14
15 import static org.mockito.ArgumentMatchers.*;
16 import static org.mockito.Mockito.*;
17
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;
24 import java.util.Set;
25 import java.util.UUID;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.ConcurrentMap;
29
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;
66
67 /**
68  * Abstract class for HomeAssistant unit tests.
69  *
70  * @author Anton Kharuzhy - Initial contribution
71  */
72 @ExtendWith(MockitoExtension.class)
73 @MockitoSettings(strictness = Strictness.LENIENT)
74 @NonNullByDefault
75 public abstract class AbstractHomeAssistantTests extends JavaTest {
76     public static final String BINDING_ID = "mqtt";
77
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);
83
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();
90
91     protected @Mock @NonNullByDefault({}) MqttBrokerConnection bridgeConnection;
92     protected @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistry;
93
94     protected @NonNullByDefault({}) MqttChannelTypeProvider channelTypeProvider;
95     protected @NonNullByDefault({}) MqttChannelStateDescriptionProvider stateDescriptionProvider;
96     protected @NonNullByDefault({}) ChannelTypeRegistry channelTypeRegistry;
97
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<>();
102
103     private @Mock @NonNullByDefault({}) TransformationService transformationService1Mock;
104
105     private @Mock @NonNullByDefault({}) BundleContext bundleContextMock;
106     private @Mock @NonNullByDefault({}) ServiceReference<TransformationService> serviceRefMock;
107
108     private @NonNullByDefault({}) TransformationHelper transformationHelper;
109
110     private final JinjaTransformationService jinjaTransformationService = new JinjaTransformationService();
111
112     @BeforeEach
113     public void beforeEachAbstractHomeAssistantTests() {
114         Mockito.when(serviceRefMock.getProperty(any())).thenReturn(JinjaTransformationProfile.PROFILE_TYPE_UID.getId());
115
116         Mockito.when(bundleContextMock.getService(serviceRefMock)).thenReturn(jinjaTransformationService);
117
118         transformationHelper = new TransformationHelper(bundleContextMock);
119         transformationHelper.setTransformationService(serviceRefMock);
120
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);
124
125         channelTypeProvider = spy(new MqttChannelTypeProvider(thingTypeRegistry, new VolatileStorageService()));
126         stateDescriptionProvider = spy(new MqttChannelStateDescriptionProvider());
127         channelTypeRegistry = spy(new ChannelTypeRegistry());
128
129         setupConnection();
130
131         // Return the mocked connection object if the bridge handler is asked for it
132         when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(bridgeConnection));
133
134         bridgeThing.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.ONLINE.NONE, ""));
135         bridgeThing.setHandler(bridgeHandler);
136
137         haThing.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.ONLINE.NONE, ""));
138     }
139
140     protected void setupConnection() {
141         doAnswer(invocation -> {
142             final var topic = (String) invocation.getArgument(0);
143             final var subscriber = (MqttMessageSubscriber) invocation.getArgument(1);
144
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());
151
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);
156
157             if (topicSubscriptions != null) {
158                 topicSubscriptions.remove(subscriber);
159             }
160             return CompletableFuture.completedFuture(true);
161         }).when(bridgeConnection).unsubscribe(any(), any());
162
163         doAnswer(invocation -> {
164             subscriptions.clear();
165             return CompletableFuture.completedFuture(true);
166         }).when(bridgeConnection).unsubscribeAll();
167
168         doReturn(CompletableFuture.completedFuture(true)).when(bridgeConnection).publish(any(), any(), anyInt(),
169                 anyBoolean());
170     }
171
172     /**
173      * @param relativePath path from src/test/java/org/openhab/binding/mqtt/homeassistant/internal
174      * @return path
175      */
176     @SuppressWarnings("null")
177     protected Path getResourcePath(String relativePath) {
178         try {
179             return Paths.get(AbstractHomeAssistantTests.class.getResource(relativePath).toURI());
180         } catch (URISyntaxException e) {
181             Assertions.fail(e);
182         }
183         throw new IllegalArgumentException();
184     }
185
186     protected String getResourceAsString(String relativePath) {
187         try {
188             return Files.readString(getResourcePath(relativePath));
189         } catch (IOException e) {
190             Assertions.fail(e);
191         }
192         throw new IllegalArgumentException();
193     }
194
195     protected byte[] getResourceAsByteArray(String relativePath) {
196         try {
197             return Files.readAllBytes(getResourcePath(relativePath));
198         } catch (IOException e) {
199             Assertions.fail(e);
200         }
201         throw new IllegalArgumentException();
202     }
203
204     protected static String configTopicToMqtt(String configTopic) {
205         return HandlerConfiguration.DEFAULT_BASETOPIC + "/" + configTopic + "/config";
206     }
207 }