2 * Copyright (c) 2010-2023 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.nest.internal.wwn.handler;
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;
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;
29 import java.util.TimeZone;
30 import java.util.function.Function;
32 import javax.ws.rs.client.ClientBuilder;
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;
86 * {@link WWNThingHandlerOSGiTest} is an abstract base class for Nest OSGi based tests.
88 * @author Wouter Born - Initial contribution
90 public abstract class WWNThingHandlerOSGiTest extends JavaOSGiTest {
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;
97 private final Logger logger = LoggerFactory.getLogger(WWNThingHandlerOSGiTest.class);
99 private static WWNTestServer server;
100 private static WWNTestApiServlet servlet = new WWNTestApiServlet();
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();
112 protected Bridge bridge;
113 protected WWNTestAccountHandler bridgeHandler;
114 protected Thing thing;
115 protected WWNBaseHandler<?> thingHandler;
116 private Class<? extends WWNBaseHandler<?>> thingClass;
118 private WWNTestHandlerFactory nestTestHandlerFactory;
119 private @NonNullByDefault({}) ClientBuilder clientBuilder;
120 private @NonNullByDefault({}) SseEventSourceFactory eventSourceFactory;
122 public WWNThingHandlerOSGiTest(Class<? extends WWNBaseHandler<?>> thingClass) {
123 this.thingClass = thingClass;
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();
134 public void setUp() throws ItemNotFoundException {
135 registerService(volatileStorageService);
137 managedThingProvider = getService(ThingProvider.class, ManagedThingProvider.class);
138 assertThat("Could not get ManagedThingProvider", managedThingProvider, is(notNullValue()));
140 thingTypeRegistry = getService(ThingTypeRegistry.class);
141 assertThat("Could not get ThingTypeRegistry", thingTypeRegistry, is(notNullValue()));
143 channelTypeRegistry = getService(ChannelTypeRegistry.class);
144 assertThat("Could not get ChannelTypeRegistry", channelTypeRegistry, is(notNullValue()));
146 channelGroupTypeRegistry = getService(ChannelGroupTypeRegistry.class);
147 assertThat("Could not get ChannelGroupTypeRegistry", channelGroupTypeRegistry, is(notNullValue()));
149 eventPublisher = getService(EventPublisher.class);
150 assertThat("Could not get EventPublisher", eventPublisher, is(notNullValue()));
152 itemFactory = getService(ItemFactory.class);
153 assertThat("Could not get ItemFactory", itemFactory, is(notNullValue()));
155 itemRegistry = getService(ItemRegistry.class);
156 assertThat("Could not get ItemRegistry", itemRegistry, is(notNullValue()));
158 managedItemChannelLinkProvider = getService(ManagedItemChannelLinkProvider.class);
159 assertThat("Could not get ManagedItemChannelLinkProvider", managedItemChannelLinkProvider, is(notNullValue()));
161 clientBuilder = getService(ClientBuilder.class);
162 assertThat("Could not get ClientBuilder", clientBuilder, is(notNullValue()));
164 eventSourceFactory = getService(SseEventSourceFactory.class);
165 assertThat("Could not get SseEventSourceFactory", eventSourceFactory, is(notNullValue()));
167 ComponentContext componentContext = mock(ComponentContext.class);
168 when(componentContext.getBundleContext()).thenReturn(bundleContext);
170 nestTestHandlerFactory = new WWNTestHandlerFactory(clientBuilder, eventSourceFactory);
171 nestTestHandlerFactory.activate(componentContext,
172 Map.of(WWNTestHandlerFactory.REDIRECT_URL_CONFIG_PROPERTY, REDIRECT_URL));
173 registerService(nestTestHandlerFactory);
175 nestTestHandlerFactory = getService(ThingHandlerFactory.class, WWNTestHandlerFactory.class);
176 assertThat("Could not get NestTestHandlerFactory", nestTestHandlerFactory, is(notNullValue()));
178 bridge = buildBridge();
179 thing = buildThing(bridge);
181 bridgeHandler = addThing(bridge, WWNTestAccountHandler.class);
182 thingHandler = addThing(thing, thingClass);
184 createAndLinkItems();
185 assertThatAllItemStatesAreNull();
189 public void tearDown() {
191 servlet.closeConnections();
194 managedThingProvider.remove(thing.getUID());
196 if (bridge != null) {
197 managedThingProvider.remove(bridge.getUID());
200 unregisterService(volatileStorageService);
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");
211 return BridgeBuilder.create(WWNTestAccountHandler.THING_TYPE_TEST_BRIDGE, "test_account")
212 .withLabel("Test Account").withConfiguration(new Configuration(properties)).build();
215 protected abstract Thing buildThing(Bridge bridge);
217 protected List<Channel> buildChannels(ThingTypeUID thingTypeUID, ThingUID thingUID) {
218 waitForAssert(() -> assertThat(thingTypeRegistry.getThingType(thingTypeUID), notNullValue()));
220 ThingType thingType = thingTypeRegistry.getThingType(thingTypeUID);
222 List<Channel> channels = new ArrayList<>();
223 channels.addAll(buildChannels(thingUID, thingType.getChannelDefinitions(), (id) -> id));
225 for (ChannelGroupDefinition channelGroupDefinition : thingType.getChannelGroupDefinitions()) {
226 ChannelGroupType channelGroupType = channelGroupTypeRegistry
227 .getChannelGroupType(channelGroupDefinition.getTypeUID());
228 String groupId = channelGroupDefinition.getId();
229 if (channelGroupType != null) {
231 buildChannels(thingUID, channelGroupType.getChannelDefinitions(), (id) -> groupId + "#" + id));
235 channels.sort((Channel c1, Channel c2) -> c1.getUID().getId().compareTo(c2.getUID().getId()));
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())
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();
264 protected String getThingId() {
265 return thing.getUID().getId();
268 protected ThingUID getThingUID() {
269 return thing.getUID();
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);
278 protected void createAndLinkItems() {
279 thing.getChannels().forEach(c -> {
280 String itemName = getItemName(c.getUID().getId());
281 Item item = itemFactory.createItem(c.getAcceptedItemType(), itemName);
283 itemRegistry.add(item);
285 managedItemChannelLinkProvider.add(new ItemChannelLink(itemName, c.getUID()));
289 protected void assertThatItemHasState(String channelId, State state) {
290 waitForAssert(() -> assertThat("Wrong state for item of channel '" + channelId + "' ", getItemState(channelId),
294 protected void assertThatItemHasNotState(String channelId, State state) {
295 waitForAssert(() -> assertThat("Wrong state for item of channel '" + channelId + "' ", getItemState(channelId),
299 protected void assertThatAllItemStatesAreNull() {
300 thing.getChannels().forEach(c -> assertThatItemHasState(c.getUID().getId(), UnDefType.NULL));
303 protected void assertThatAllItemStatesAreNotNull() {
304 thing.getChannels().forEach(c -> assertThatItemHasNotState(c.getUID().getId(), UnDefType.NULL));
307 protected ChannelUID getChannelUID(String channelId) {
308 return new ChannelUID(getThingUID(), channelId);
311 protected String getItemName(String channelId) {
312 return getThingId() + "_" + channelId.replaceAll("#", "_");
315 private State getItemState(String channelId) {
316 String itemName = getItemName(channelId);
318 return itemRegistry.getItem(itemName).getState();
319 } catch (ItemNotFoundException e) {
320 throw new AssertionError("Item with name '" + itemName + "' not found");
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));
332 protected void updateAllItemStatesToNull() {
333 thing.getChannels().forEach(c -> updateItemState(c.getUID().getId(), UnDefType.NULL));
336 protected void refreshAllChannels() {
337 thing.getChannels().forEach(c -> thingHandler.handleCommand(c.getUID(), RefreshType.REFRESH));
340 protected void handleCommand(String channelId, Command command) {
341 thingHandler.handleCommand(getChannelUID(channelId), command);
344 protected void updateItemState(String channelId, State state) {
345 String itemName = getItemName(channelId);
346 eventPublisher.post(ItemEventFactory.createStateEvent(itemName, state));
349 protected void assertNestApiPropertyState(String nestId, String propertyName, String state) {
350 waitForAssert(() -> assertThat(servlet.getNestIdPropertyState(nestId, propertyName), is(state)));
353 public static DateTimeType parseDateTimeType(String text) {
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);