]> git.basschouten.com Git - openhab-addons.git/blob
7ad42385f404451a1e2ad262566d124026805f12
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.nest.internal.wwn.handler;
14
15 import static org.hamcrest.CoreMatchers.*;
16 import static org.hamcrest.MatcherAssert.assertThat;
17 import static org.hamcrest.core.Is.is;
18 import static org.hamcrest.core.IsNot.not;
19 import static org.mockito.Mockito.*;
20 import static org.openhab.binding.nest.internal.wwn.rest.WWNStreamingRestClient.PUT;
21
22 import java.io.IOException;
23 import java.time.Instant;
24 import java.time.format.DateTimeParseException;
25 import java.util.ArrayList;
26 import java.util.HashMap;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.TimeZone;
30 import java.util.function.Function;
31
32 import javax.ws.rs.client.ClientBuilder;
33
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jetty.servlet.ServletHolder;
36 import org.junit.jupiter.api.AfterEach;
37 import org.junit.jupiter.api.BeforeAll;
38 import org.junit.jupiter.api.BeforeEach;
39 import org.openhab.binding.nest.internal.wwn.config.WWNAccountConfiguration;
40 import org.openhab.binding.nest.internal.wwn.test.WWNTestAccountHandler;
41 import org.openhab.binding.nest.internal.wwn.test.WWNTestApiServlet;
42 import org.openhab.binding.nest.internal.wwn.test.WWNTestHandlerFactory;
43 import org.openhab.binding.nest.internal.wwn.test.WWNTestServer;
44 import org.openhab.core.config.core.Configuration;
45 import org.openhab.core.events.EventPublisher;
46 import org.openhab.core.items.Item;
47 import org.openhab.core.items.ItemFactory;
48 import org.openhab.core.items.ItemNotFoundException;
49 import org.openhab.core.items.ItemRegistry;
50 import org.openhab.core.items.events.ItemEventFactory;
51 import org.openhab.core.library.types.DateTimeType;
52 import org.openhab.core.test.TestPortUtil;
53 import org.openhab.core.test.java.JavaOSGiTest;
54 import org.openhab.core.test.storage.VolatileStorageService;
55 import org.openhab.core.thing.Bridge;
56 import org.openhab.core.thing.Channel;
57 import org.openhab.core.thing.ChannelUID;
58 import org.openhab.core.thing.ManagedThingProvider;
59 import org.openhab.core.thing.Thing;
60 import org.openhab.core.thing.ThingProvider;
61 import org.openhab.core.thing.ThingTypeUID;
62 import org.openhab.core.thing.ThingUID;
63 import org.openhab.core.thing.binding.ThingHandlerFactory;
64 import org.openhab.core.thing.binding.builder.BridgeBuilder;
65 import org.openhab.core.thing.binding.builder.ChannelBuilder;
66 import org.openhab.core.thing.link.ItemChannelLink;
67 import org.openhab.core.thing.link.ManagedItemChannelLinkProvider;
68 import org.openhab.core.thing.type.ChannelDefinition;
69 import org.openhab.core.thing.type.ChannelGroupDefinition;
70 import org.openhab.core.thing.type.ChannelGroupType;
71 import org.openhab.core.thing.type.ChannelGroupTypeRegistry;
72 import org.openhab.core.thing.type.ChannelType;
73 import org.openhab.core.thing.type.ChannelTypeRegistry;
74 import org.openhab.core.thing.type.ThingType;
75 import org.openhab.core.thing.type.ThingTypeRegistry;
76 import org.openhab.core.types.Command;
77 import org.openhab.core.types.RefreshType;
78 import org.openhab.core.types.State;
79 import org.openhab.core.types.UnDefType;
80 import org.osgi.service.component.ComponentContext;
81 import org.osgi.service.jaxrs.client.SseEventSourceFactory;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
84
85 /**
86  * {@link WWNThingHandlerOSGiTest} is an abstract base class for Nest OSGi based tests.
87  *
88  * @author Wouter Born - Initial contribution
89  */
90 public abstract class WWNThingHandlerOSGiTest extends JavaOSGiTest {
91
92     private static final String SERVER_HOST = "127.0.0.1";
93     private static final int SERVER_PORT = TestPortUtil.findFreePort();
94     private static final int SERVER_TIMEOUT = -1;
95     private static final String REDIRECT_URL = "http://" + SERVER_HOST + ":" + SERVER_PORT;
96
97     private final Logger logger = LoggerFactory.getLogger(WWNThingHandlerOSGiTest.class);
98
99     private static WWNTestServer server;
100     private static WWNTestApiServlet servlet = new WWNTestApiServlet();
101
102     private ChannelTypeRegistry channelTypeRegistry;
103     private ChannelGroupTypeRegistry channelGroupTypeRegistry;
104     private ItemFactory itemFactory;
105     private ItemRegistry itemRegistry;
106     private EventPublisher eventPublisher;
107     private ManagedThingProvider managedThingProvider;
108     private ThingTypeRegistry thingTypeRegistry;
109     private ManagedItemChannelLinkProvider managedItemChannelLinkProvider;
110     private VolatileStorageService volatileStorageService = new VolatileStorageService();
111
112     protected Bridge bridge;
113     protected WWNTestAccountHandler bridgeHandler;
114     protected Thing thing;
115     protected WWNBaseHandler<?> thingHandler;
116     private Class<? extends WWNBaseHandler<?>> thingClass;
117
118     private WWNTestHandlerFactory nestTestHandlerFactory;
119     private @NonNullByDefault({}) ClientBuilder clientBuilder;
120     private @NonNullByDefault({}) SseEventSourceFactory eventSourceFactory;
121
122     public WWNThingHandlerOSGiTest(Class<? extends WWNBaseHandler<?>> thingClass) {
123         this.thingClass = thingClass;
124     }
125
126     @BeforeAll
127     public static void setUpClass() throws Exception {
128         ServletHolder holder = new ServletHolder(servlet);
129         server = new WWNTestServer(SERVER_HOST, SERVER_PORT, SERVER_TIMEOUT, holder);
130         server.startServer();
131     }
132
133     @BeforeEach
134     public void setUp() throws ItemNotFoundException {
135         registerService(volatileStorageService);
136
137         managedThingProvider = getService(ThingProvider.class, ManagedThingProvider.class);
138         assertThat("Could not get ManagedThingProvider", managedThingProvider, is(notNullValue()));
139
140         thingTypeRegistry = getService(ThingTypeRegistry.class);
141         assertThat("Could not get ThingTypeRegistry", thingTypeRegistry, is(notNullValue()));
142
143         channelTypeRegistry = getService(ChannelTypeRegistry.class);
144         assertThat("Could not get ChannelTypeRegistry", channelTypeRegistry, is(notNullValue()));
145
146         channelGroupTypeRegistry = getService(ChannelGroupTypeRegistry.class);
147         assertThat("Could not get ChannelGroupTypeRegistry", channelGroupTypeRegistry, is(notNullValue()));
148
149         eventPublisher = getService(EventPublisher.class);
150         assertThat("Could not get EventPublisher", eventPublisher, is(notNullValue()));
151
152         itemFactory = getService(ItemFactory.class);
153         assertThat("Could not get ItemFactory", itemFactory, is(notNullValue()));
154
155         itemRegistry = getService(ItemRegistry.class);
156         assertThat("Could not get ItemRegistry", itemRegistry, is(notNullValue()));
157
158         managedItemChannelLinkProvider = getService(ManagedItemChannelLinkProvider.class);
159         assertThat("Could not get ManagedItemChannelLinkProvider", managedItemChannelLinkProvider, is(notNullValue()));
160
161         clientBuilder = getService(ClientBuilder.class);
162         assertThat("Could not get ClientBuilder", clientBuilder, is(notNullValue()));
163
164         eventSourceFactory = getService(SseEventSourceFactory.class);
165         assertThat("Could not get SseEventSourceFactory", eventSourceFactory, is(notNullValue()));
166
167         ComponentContext componentContext = mock(ComponentContext.class);
168         when(componentContext.getBundleContext()).thenReturn(bundleContext);
169
170         nestTestHandlerFactory = new WWNTestHandlerFactory(clientBuilder, eventSourceFactory);
171         nestTestHandlerFactory.activate(componentContext,
172                 Map.of(WWNTestHandlerFactory.REDIRECT_URL_CONFIG_PROPERTY, REDIRECT_URL));
173         registerService(nestTestHandlerFactory);
174
175         nestTestHandlerFactory = getService(ThingHandlerFactory.class, WWNTestHandlerFactory.class);
176         assertThat("Could not get NestTestHandlerFactory", nestTestHandlerFactory, is(notNullValue()));
177
178         bridge = buildBridge();
179         thing = buildThing(bridge);
180
181         bridgeHandler = addThing(bridge, WWNTestAccountHandler.class);
182         thingHandler = addThing(thing, thingClass);
183
184         createAndLinkItems();
185         assertThatAllItemStatesAreNull();
186     }
187
188     @AfterEach
189     public void tearDown() {
190         servlet.reset();
191         servlet.closeConnections();
192
193         if (thing != null) {
194             managedThingProvider.remove(thing.getUID());
195         }
196         if (bridge != null) {
197             managedThingProvider.remove(bridge.getUID());
198         }
199
200         unregisterService(volatileStorageService);
201     }
202
203     protected Bridge buildBridge() {
204         Map<String, Object> properties = new HashMap<>();
205         properties.put(WWNAccountConfiguration.ACCESS_TOKEN,
206                 "c.eQ5QBBPiFOTNzPHbmZPcE9yPZ7GayzLusifgQR2DQRFNyUS9ESvlhJF0D7vG8Y0TFV39zX1vIOsWrv8RKCMrFepNUb9FqHEboa4MtWLUsGb4tD9oBh0jrV4HooJUmz5sVA5KZR0dkxyLYyPc");
207         properties.put(WWNAccountConfiguration.PINCODE, "64P2XRYT");
208         properties.put(WWNAccountConfiguration.PRODUCT_ID, "8fdf9885-ca07-4252-1aa3-f3d5ca9589e0");
209         properties.put(WWNAccountConfiguration.PRODUCT_SECRET, "QITLR3iyUlWaj9dbvCxsCKp4f");
210
211         return BridgeBuilder.create(WWNTestAccountHandler.THING_TYPE_TEST_BRIDGE, "test_account")
212                 .withLabel("Test Account").withConfiguration(new Configuration(properties)).build();
213     }
214
215     protected abstract Thing buildThing(Bridge bridge);
216
217     protected List<Channel> buildChannels(ThingTypeUID thingTypeUID, ThingUID thingUID) {
218         waitForAssert(() -> assertThat(thingTypeRegistry.getThingType(thingTypeUID), notNullValue()));
219
220         ThingType thingType = thingTypeRegistry.getThingType(thingTypeUID);
221
222         List<Channel> channels = new ArrayList<>();
223         channels.addAll(buildChannels(thingUID, thingType.getChannelDefinitions(), (id) -> id));
224
225         for (ChannelGroupDefinition channelGroupDefinition : thingType.getChannelGroupDefinitions()) {
226             ChannelGroupType channelGroupType = channelGroupTypeRegistry
227                     .getChannelGroupType(channelGroupDefinition.getTypeUID());
228             String groupId = channelGroupDefinition.getId();
229             if (channelGroupType != null) {
230                 channels.addAll(
231                         buildChannels(thingUID, channelGroupType.getChannelDefinitions(), (id) -> groupId + "#" + id));
232             }
233         }
234
235         channels.sort((Channel c1, Channel c2) -> c1.getUID().getId().compareTo(c2.getUID().getId()));
236         return channels;
237     }
238
239     protected List<Channel> buildChannels(ThingUID thingUID, List<ChannelDefinition> channelDefinitions,
240             Function<String, String> channelIdFunction) {
241         List<Channel> result = new ArrayList<>();
242         for (ChannelDefinition channelDefinition : channelDefinitions) {
243             ChannelType channelType = channelTypeRegistry.getChannelType(channelDefinition.getChannelTypeUID());
244             if (channelType != null) {
245                 result.add(ChannelBuilder
246                         .create(new ChannelUID(thingUID, channelIdFunction.apply(channelDefinition.getId())),
247                                 channelType.getItemType())
248                         .build());
249             }
250         }
251         return result;
252     }
253
254     @SuppressWarnings("unchecked")
255     protected <T> T addThing(Thing thing, Class<T> thingHandlerClass) {
256         assertThat(thing.getHandler(), is(nullValue()));
257         managedThingProvider.add(thing);
258         waitForAssert(() -> assertThat(thing.getHandler(), notNullValue()));
259         assertThat(thing.getConfiguration(), is(notNullValue()));
260         assertThat(thing.getHandler(), is(instanceOf(thingHandlerClass)));
261         return (T) thing.getHandler();
262     }
263
264     protected String getThingId() {
265         return thing.getUID().getId();
266     }
267
268     protected ThingUID getThingUID() {
269         return thing.getUID();
270     }
271
272     protected void putStreamingEventData(String json) throws IOException {
273         String singleLineJson = json.replaceAll("\n\r\\s+", "").replaceAll("\n\\s+", "").replaceAll("\n\r", "")
274                 .replaceAll("\n", "");
275         servlet.queueEvent(PUT, singleLineJson);
276     }
277
278     protected void createAndLinkItems() {
279         thing.getChannels().forEach(c -> {
280             String itemName = getItemName(c.getUID().getId());
281             Item item = itemFactory.createItem(c.getAcceptedItemType(), itemName);
282             if (item != null) {
283                 itemRegistry.add(item);
284             }
285             managedItemChannelLinkProvider.add(new ItemChannelLink(itemName, c.getUID()));
286         });
287     }
288
289     protected void assertThatItemHasState(String channelId, State state) {
290         waitForAssert(() -> assertThat("Wrong state for item of channel '" + channelId + "' ", getItemState(channelId),
291                 is(state)));
292     }
293
294     protected void assertThatItemHasNotState(String channelId, State state) {
295         waitForAssert(() -> assertThat("Wrong state for item of channel '" + channelId + "' ", getItemState(channelId),
296                 is(not(state))));
297     }
298
299     protected void assertThatAllItemStatesAreNull() {
300         thing.getChannels().forEach(c -> assertThatItemHasState(c.getUID().getId(), UnDefType.NULL));
301     }
302
303     protected void assertThatAllItemStatesAreNotNull() {
304         thing.getChannels().forEach(c -> assertThatItemHasNotState(c.getUID().getId(), UnDefType.NULL));
305     }
306
307     protected ChannelUID getChannelUID(String channelId) {
308         return new ChannelUID(getThingUID(), channelId);
309     }
310
311     protected String getItemName(String channelId) {
312         return getThingId() + "_" + channelId.replaceAll("#", "_");
313     }
314
315     private State getItemState(String channelId) {
316         String itemName = getItemName(channelId);
317         try {
318             return itemRegistry.getItem(itemName).getState();
319         } catch (ItemNotFoundException e) {
320             throw new AssertionError("Item with name '" + itemName + "' not found");
321         }
322     }
323
324     protected void logItemStates() {
325         thing.getChannels().forEach(c -> {
326             String channelId = c.getUID().getId();
327             String itemName = getItemName(channelId);
328             logger.debug("{} = {}", itemName, getItemState(channelId));
329         });
330     }
331
332     protected void updateAllItemStatesToNull() {
333         thing.getChannels().forEach(c -> updateItemState(c.getUID().getId(), UnDefType.NULL));
334     }
335
336     protected void refreshAllChannels() {
337         thing.getChannels().forEach(c -> thingHandler.handleCommand(c.getUID(), RefreshType.REFRESH));
338     }
339
340     protected void handleCommand(String channelId, Command command) {
341         thingHandler.handleCommand(getChannelUID(channelId), command);
342     }
343
344     protected void updateItemState(String channelId, State state) {
345         String itemName = getItemName(channelId);
346         eventPublisher.post(ItemEventFactory.createStateEvent(itemName, state));
347     }
348
349     protected void assertNestApiPropertyState(String nestId, String propertyName, String state) {
350         waitForAssert(() -> assertThat(servlet.getNestIdPropertyState(nestId, propertyName), is(state)));
351     }
352
353     public static DateTimeType parseDateTimeType(String text) {
354         try {
355             return new DateTimeType(Instant.parse(text).atZone(TimeZone.getDefault().toZoneId()));
356         } catch (DateTimeParseException e) {
357             throw new IllegalArgumentException("Invalid date time argument: " + text, e);
358         }
359     }
360 }