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.modbus.tests;
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.IsInstanceOf.instanceOf;
19 import static org.junit.jupiter.api.Assertions.*;
20 import static org.mockito.ArgumentMatchers.any;
21 import static org.mockito.Mockito.*;
23 import java.util.ArrayList;
24 import java.util.Collections;
25 import java.util.Dictionary;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Hashtable;
29 import java.util.List;
33 import org.eclipse.jdt.annotation.NonNull;
34 import org.eclipse.jdt.annotation.NonNullByDefault;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.junit.jupiter.api.AfterEach;
37 import org.junit.jupiter.api.BeforeEach;
38 import org.junit.jupiter.api.extension.ExtendWith;
39 import org.mockito.Mock;
40 import org.mockito.Mockito;
41 import org.mockito.junit.jupiter.MockitoExtension;
42 import org.mockito.junit.jupiter.MockitoSettings;
43 import org.mockito.quality.Strictness;
44 import org.openhab.binding.modbus.internal.ModbusHandlerFactory;
45 import org.openhab.core.events.Event;
46 import org.openhab.core.events.EventFilter;
47 import org.openhab.core.events.EventSubscriber;
48 import org.openhab.core.io.transport.modbus.ModbusCommunicationInterface;
49 import org.openhab.core.io.transport.modbus.ModbusManager;
50 import org.openhab.core.items.Item;
51 import org.openhab.core.items.ItemProvider;
52 import org.openhab.core.items.ItemRegistry;
53 import org.openhab.core.items.ManagedItemProvider;
54 import org.openhab.core.items.events.ItemStateEvent;
55 import org.openhab.core.library.CoreItemFactory;
56 import org.openhab.core.test.java.JavaOSGiTest;
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.binding.ThingHandler;
62 import org.openhab.core.thing.binding.ThingHandlerFactory;
63 import org.openhab.core.thing.link.AbstractLink;
64 import org.openhab.core.thing.link.ItemChannelLink;
65 import org.openhab.core.thing.link.ItemChannelLinkProvider;
66 import org.openhab.core.thing.link.ItemChannelLinkRegistry;
67 import org.openhab.core.thing.link.ManagedItemChannelLinkProvider;
68 import org.openhab.core.thing.type.ChannelTypeUID;
69 import org.openhab.core.transform.TransformationService;
70 import org.openhab.core.types.State;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
75 * @author Sami Salonen - Initial contribution
77 @ExtendWith(MockitoExtension.class)
78 @MockitoSettings(strictness = Strictness.LENIENT)
80 public abstract class AbstractModbusOSGiTest extends JavaOSGiTest {
83 * When Mockito is used for mocking {@link ThingHandler}s it has to be able to load the {@link ChannelTypeUID}
84 * class. Bnd will add the package to the generated manifest when the class is referenced here.
86 static void mockitoPackageImport() {
87 ChannelTypeUID.class.getClass();
90 private static class StateSubscriber implements EventSubscriber {
92 private final Logger logger = LoggerFactory.getLogger(StateSubscriber.class);
94 public Map<String, List<State>> stateUpdates = new HashMap<>();
97 public Set<@NonNull String> getSubscribedEventTypes() {
98 return Collections.singleton(ItemStateEvent.TYPE);
102 public @Nullable EventFilter getEventFilter() {
107 public void receive(Event event) {
108 // Expecting only state updates in the tests
109 assertThat(event, is(instanceOf(ItemStateEvent.class)));
110 ItemStateEvent stateEvent = (ItemStateEvent) event;
111 logger.trace("Captured event: {} of type {}. Payload: {}", event,
112 stateEvent.getItemState().getClass().getSimpleName(), event.getPayload());
113 stateUpdates.computeIfAbsent(stateEvent.getItemName(), item -> new ArrayList<>())
114 .add(stateEvent.getItemState());
118 private final Logger logger = LoggerFactory.getLogger(AbstractModbusOSGiTest.class);
120 protected @Mock @NonNullByDefault({}) ModbusManager mockedModbusManager;
121 protected @NonNullByDefault({}) ModbusManager realModbusManager;
122 protected @NonNullByDefault({}) ManagedThingProvider thingProvider;
123 protected @NonNullByDefault({}) ManagedItemProvider itemProvider;
124 protected @NonNullByDefault({}) ManagedItemChannelLinkProvider itemChannelLinkProvider;
125 protected @NonNullByDefault({}) ItemRegistry itemRegistry;
126 protected @NonNullByDefault({}) ItemChannelLinkRegistry itemChannelLinkRegistry;
127 protected @NonNullByDefault({}) CoreItemFactory coreItemFactory;
129 private Set<Item> addedItems = new HashSet<>();
130 private Set<Thing> addedThings = new HashSet<>();
131 private Set<ItemChannelLink> addedLinks = new HashSet<>();
132 private StateSubscriber stateSubscriber = new StateSubscriber();
134 protected @Mock @NonNullByDefault({}) ModbusCommunicationInterface comms;
137 * Before each test, configure mocked services
140 public void setUpAbstractModbusOSGiTest() {
141 logger.debug("setUpAbstractModbusOSGiTest BEGIN");
142 registerVolatileStorageService();
143 registerService(mockedModbusManager);
144 registerService(stateSubscriber);
146 swapModbusManagerToMocked();
148 thingProvider = getService(ThingProvider.class, ManagedThingProvider.class);
149 assertThat("Could not get ManagedThingProvider", thingProvider, is(notNullValue()));
150 itemProvider = getService(ItemProvider.class, ManagedItemProvider.class);
151 assertThat("Could not get ManagedItemProvider", itemProvider, is(notNullValue()));
152 itemChannelLinkProvider = getService(ItemChannelLinkProvider.class, ManagedItemChannelLinkProvider.class);
153 assertThat("Could not get ManagedItemChannelLinkProvider", itemChannelLinkProvider, is(notNullValue()));
154 itemRegistry = getService(ItemRegistry.class);
155 assertThat("Could not get ItemRegistry", itemRegistry, is(notNullValue()));
156 itemChannelLinkRegistry = getService(ItemChannelLinkRegistry.class);
157 assertThat("Could not get ItemChannelLinkRegistry", itemChannelLinkRegistry, is(notNullValue()));
159 coreItemFactory = new CoreItemFactory();
161 // Clean slate for all tests
162 reset(mockedModbusManager);
164 stateSubscriber.stateUpdates.clear();
165 logger.debug("setUpAbstractModbusOSGiTest END");
169 public void tearDownAbstractModbusOSGiTest() throws Exception {
170 logger.debug("tearDownAbstractModbusOSGiTest BEGIN");
171 swapModbusManagerToReal();
172 for (Item item : addedItems) {
173 assertNotNull(itemProvider.remove(item.getName()));
175 for (Thing thing : addedThings) {
178 for (ItemChannelLink link : addedLinks) {
179 logger.debug("Unlinking {} <-> {}", link.getItemName(), link.getLinkedUID());
180 assertNotNull(itemChannelLinkProvider.remove(link.getUID()));
182 logger.debug("tearDownAbstractModbusOSGiTest END");
185 protected void addThing(Thing thing) {
186 assertThat(addedThings.contains(thing), not(equalTo(true)));
187 ThingHandler mockHandler = thing.getHandler();
188 if (mockHandler != null) {
189 // If there is a handler attached to fresh thing, it should be mocked (this pattern is used with some tests)
190 assertThat(Mockito.mockingDetails(thing.getHandler()).isMock(), is(equalTo(true)));
193 thingProvider.add(thing);
194 waitForAssert(() -> assertThat(thing.getHandler(), notNullValue()));
195 assertThat(thing.getConfiguration(), is(notNullValue()));
196 addedThings.add(thing);
197 if (mockHandler != null) {
198 // Re-attach mock handler
199 ThingHandler realHandlerInitedByCore = thing.getHandler();
200 assertNotNull(realHandlerInitedByCore);
201 assertNotSame(realHandlerInitedByCore, mockHandler);
202 realHandlerInitedByCore.dispose();
203 thing.setHandler(mockHandler);
207 protected void disposeThing(Thing thing) {
208 thingProvider.remove(thing.getUID());
211 protected void addItem(Item item) {
212 assertThat(addedItems.contains(item), not(equalTo(true)));
213 itemProvider.add(item);
214 addedItems.add(item);
217 protected void linkItem(String itemName, ChannelUID channelUID) {
218 logger.debug("Linking {} <-> {}", itemName, channelUID);
219 ItemChannelLink link = new ItemChannelLink(itemName, channelUID);
220 assertThat(addedLinks.contains(link), not(equalTo(true)));
221 itemChannelLinkProvider.add(link);
222 waitForAssert(() -> assertThat(itemChannelLinkRegistry.get(AbstractLink.getIDFor(itemName, channelUID)),
223 is(notNullValue())));
224 addedLinks.add(link);
227 protected @Nullable List<State> getStateUpdates(String itemName) {
228 return stateSubscriber.stateUpdates.get(itemName);
231 protected void mockTransformation(String name, TransformationService service) {
232 Dictionary<String, Object> params = new Hashtable<>();
233 params.put("openhab.transform", name);
234 registerService(service, params);
237 protected void mockCommsToModbusManager() {
238 assert comms != null;
239 doReturn(comms).when(mockedModbusManager).newModbusCommunicationInterface(any(), any());
242 protected void swapModbusManagerToMocked() {
243 assertNull(realModbusManager);
244 realModbusManager = getService(ModbusManager.class);
245 assertThat("Could not get ModbusManager", realModbusManager, is(notNullValue()));
246 assertThat("Could not get ModbusManagerImpl", realModbusManager.getClass().getSimpleName(),
247 is(equalTo("ModbusManagerImpl")));
248 assertNotNull(realModbusManager);
250 ModbusHandlerFactory modbusHandlerFactory = getService(ThingHandlerFactory.class, ModbusHandlerFactory.class);
251 assertThat("Could not get ModbusHandlerFactory", modbusHandlerFactory, is(notNullValue()));
252 assertNotNull(modbusHandlerFactory);
253 modbusHandlerFactory.unsetModbusManager(realModbusManager);
254 modbusHandlerFactory.setModbusManager(mockedModbusManager);
257 protected void swapModbusManagerToReal() {
258 assertNotNull(realModbusManager);
259 ModbusHandlerFactory modbusHandlerFactory = getService(ThingHandlerFactory.class, ModbusHandlerFactory.class);
260 assertThat("Could not get ModbusHandlerFactory", modbusHandlerFactory, is(notNullValue()));
261 assertNotNull(modbusHandlerFactory);
262 modbusHandlerFactory.unsetModbusManager(mockedModbusManager);
263 modbusHandlerFactory.setModbusManager(realModbusManager);