]> git.basschouten.com Git - openhab-addons.git/blob
49879ac8c6a2c707d9d70f0f7156ec2fe084e688
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.Mockito.any;
16 import static org.mockito.Mockito.anyBoolean;
17 import static org.mockito.Mockito.anyInt;
18 import static org.mockito.Mockito.doAnswer;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.spy;
21 import static org.mockito.Mockito.when;
22
23 import java.io.IOException;
24 import java.net.URISyntaxException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.nio.file.Paths;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.UUID;
33 import java.util.concurrent.CompletableFuture;
34
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.junit.jupiter.api.Assertions;
37 import org.junit.jupiter.api.BeforeEach;
38 import org.junit.jupiter.api.extension.ExtendWith;
39 import org.mockito.Mock;
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.MqttChannelTypeProvider;
44 import org.openhab.binding.mqtt.generic.TransformationServiceProvider;
45 import org.openhab.binding.mqtt.handler.BrokerHandler;
46 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
47 import org.openhab.core.io.transport.mqtt.MqttMessageSubscriber;
48 import org.openhab.core.test.java.JavaTest;
49 import org.openhab.core.thing.Bridge;
50 import org.openhab.core.thing.Thing;
51 import org.openhab.core.thing.ThingStatus;
52 import org.openhab.core.thing.ThingStatusDetail;
53 import org.openhab.core.thing.ThingStatusInfo;
54 import org.openhab.core.thing.ThingTypeUID;
55 import org.openhab.core.thing.ThingUID;
56 import org.openhab.core.thing.binding.builder.BridgeBuilder;
57 import org.openhab.core.thing.binding.builder.ThingBuilder;
58 import org.openhab.core.thing.type.ThingTypeBuilder;
59 import org.openhab.core.thing.type.ThingTypeRegistry;
60 import org.openhab.transform.jinja.internal.JinjaTransformationService;
61 import org.openhab.transform.jinja.internal.profiles.JinjaTransformationProfile;
62
63 /**
64  * Abstract class for HomeAssistant unit tests.
65  *
66  * @author Anton Kharuzhy - Initial contribution
67  */
68 @SuppressWarnings({ "ConstantConditions" })
69 @ExtendWith(MockitoExtension.class)
70 @MockitoSettings(strictness = Strictness.WARN)
71 @NonNullByDefault
72 public abstract class AbstractHomeAssistantTests extends JavaTest {
73     public static final String BINDING_ID = "mqtt";
74
75     public static final String BRIDGE_TYPE_ID = "broker";
76     public static final String BRIDGE_TYPE_LABEL = "MQTT Broker";
77     public static final ThingTypeUID BRIDGE_TYPE_UID = new ThingTypeUID(BINDING_ID, BRIDGE_TYPE_ID);
78     public static final String BRIDGE_ID = UUID.randomUUID().toString();
79     public static final ThingUID BRIDGE_UID = new ThingUID(BRIDGE_TYPE_UID, BRIDGE_ID);
80
81     public static final String HA_TYPE_ID = "homeassistant";
82     public static final String HA_TYPE_LABEL = "Homeassistant";
83     public static final ThingTypeUID HA_TYPE_UID = new ThingTypeUID(BINDING_ID, HA_TYPE_ID);
84     public static final String HA_ID = UUID.randomUUID().toString();
85     public static final ThingUID HA_UID = new ThingUID(HA_TYPE_UID, HA_ID);
86
87     protected @Mock @NonNullByDefault({}) MqttBrokerConnection bridgeConnection;
88     protected @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistry;
89     protected @Mock @NonNullByDefault({}) TransformationServiceProvider transformationServiceProvider;
90
91     @SuppressWarnings("NotNullFieldNotInitialized")
92     protected @NonNullByDefault({}) MqttChannelTypeProvider channelTypeProvider;
93
94     protected final Bridge bridgeThing = BridgeBuilder.create(BRIDGE_TYPE_UID, BRIDGE_UID).build();
95     protected final BrokerHandler bridgeHandler = spy(new BrokerHandler(bridgeThing));
96     protected final Thing haThing = ThingBuilder.create(HA_TYPE_UID, HA_UID).withBridge(BRIDGE_UID).build();
97     protected final Map<String, Set<MqttMessageSubscriber>> subscriptions = new HashMap<>();
98
99     private final JinjaTransformationService jinjaTransformationService = new JinjaTransformationService();
100
101     @BeforeEach
102     public void beforeEachAbstractHomeAssistantTests() {
103         when(thingTypeRegistry.getThingType(BRIDGE_TYPE_UID))
104                 .thenReturn(ThingTypeBuilder.instance(BRIDGE_TYPE_UID, BRIDGE_TYPE_LABEL).build());
105         when(thingTypeRegistry.getThingType(HA_TYPE_UID))
106                 .thenReturn(ThingTypeBuilder.instance(HA_TYPE_UID, HA_TYPE_LABEL).build());
107         when(transformationServiceProvider
108                 .getTransformationService(JinjaTransformationProfile.PROFILE_TYPE_UID.getId()))
109                         .thenReturn(jinjaTransformationService);
110
111         channelTypeProvider = spy(new MqttChannelTypeProvider(thingTypeRegistry));
112
113         setupConnection();
114
115         // Return the mocked connection object if the bridge handler is asked for it
116         when(bridgeHandler.getConnectionAsync()).thenReturn(CompletableFuture.completedFuture(bridgeConnection));
117
118         bridgeThing.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.ONLINE.NONE, ""));
119         bridgeThing.setHandler(bridgeHandler);
120
121         haThing.setStatusInfo(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.ONLINE.NONE, ""));
122     }
123
124     protected void setupConnection() {
125         doAnswer(invocation -> {
126             final var topic = (String) invocation.getArgument(0);
127             final var subscriber = (MqttMessageSubscriber) invocation.getArgument(1);
128             final var topicSubscriptions = subscriptions.getOrDefault(topic, new HashSet<>());
129
130             topicSubscriptions.add(subscriber);
131             subscriptions.put(topic, topicSubscriptions);
132             return CompletableFuture.completedFuture(true);
133         }).when(bridgeConnection).subscribe(any(), any());
134
135         doAnswer(invocation -> {
136             final var topic = (String) invocation.getArgument(0);
137             final var subscriber = (MqttMessageSubscriber) invocation.getArgument(1);
138             final var topicSubscriptions = subscriptions.get(topic);
139
140             if (topicSubscriptions != null) {
141                 topicSubscriptions.remove(subscriber);
142             }
143             return CompletableFuture.completedFuture(true);
144         }).when(bridgeConnection).unsubscribe(any(), any());
145
146         doAnswer(invocation -> {
147             subscriptions.clear();
148             return CompletableFuture.completedFuture(true);
149         }).when(bridgeConnection).unsubscribeAll();
150
151         doReturn(CompletableFuture.completedFuture(true)).when(bridgeConnection).publish(any(), any(), anyInt(),
152                 anyBoolean());
153     }
154
155     /**
156      * @param relativePath path from src/test/java/org/openhab/binding/mqtt/homeassistant/internal
157      * @return path
158      */
159     protected Path getResourcePath(String relativePath) {
160         try {
161             return Paths.get(AbstractHomeAssistantTests.class.getResource(relativePath).toURI());
162         } catch (URISyntaxException e) {
163             Assertions.fail(e);
164         }
165         throw new IllegalArgumentException();
166     }
167
168     protected String getResourceAsString(String relativePath) {
169         try {
170             return Files.readString(getResourcePath(relativePath));
171         } catch (IOException e) {
172             Assertions.fail(e);
173         }
174         throw new IllegalArgumentException();
175     }
176
177     protected byte[] getResourceAsByteArray(String relativePath) {
178         try {
179             return Files.readAllBytes(getResourcePath(relativePath));
180         } catch (IOException e) {
181             Assertions.fail(e);
182         }
183         throw new IllegalArgumentException();
184     }
185
186     protected static String configTopicToMqtt(String configTopic) {
187         return HandlerConfiguration.DEFAULT_BASETOPIC + "/" + configTopic + "/config";
188     }
189 }