2 * Copyright (c) 2010-2022 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.ItemChannelLink;
64 import org.openhab.core.thing.link.ItemChannelLinkProvider;
65 import org.openhab.core.thing.link.ManagedItemChannelLinkProvider;
66 import org.openhab.core.thing.type.ChannelTypeUID;
67 import org.openhab.core.transform.TransformationService;
68 import org.openhab.core.types.State;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * @author Sami Salonen - Initial contribution
75 @ExtendWith(MockitoExtension.class)
76 @MockitoSettings(strictness = Strictness.LENIENT)
78 public abstract class AbstractModbusOSGiTest extends JavaOSGiTest {
81 * When Mockito is used for mocking {@link ThingHandler}s it has to be able to load the {@link ChannelTypeUID}
82 * class. Bnd will add the package to the generated manifest when the class is referenced here.
84 static void mockitoPackageImport() {
85 ChannelTypeUID.class.getClass();
88 private static class StateSubscriber implements EventSubscriber {
90 private final Logger logger = LoggerFactory.getLogger(StateSubscriber.class);
92 public Map<String, List<State>> stateUpdates = new HashMap<>();
95 public Set<@NonNull String> getSubscribedEventTypes() {
96 return Collections.singleton(ItemStateEvent.TYPE);
100 public @Nullable EventFilter getEventFilter() {
105 public void receive(Event event) {
106 // Expecting only state updates in the tests
107 assertThat(event, is(instanceOf(ItemStateEvent.class)));
108 ItemStateEvent stateEvent = (ItemStateEvent) event;
109 logger.trace("Captured event: {} of type {}. Payload: {}", event,
110 stateEvent.getItemState().getClass().getSimpleName(), event.getPayload());
111 stateUpdates.computeIfAbsent(stateEvent.getItemName(), (item) -> new ArrayList<>())
112 .add(stateEvent.getItemState());
116 private final Logger logger = LoggerFactory.getLogger(AbstractModbusOSGiTest.class);
118 protected @Mock @NonNullByDefault({}) ModbusManager mockedModbusManager;
119 protected @NonNullByDefault({}) ModbusManager realModbusManager;
120 protected @NonNullByDefault({}) ManagedThingProvider thingProvider;
121 protected @NonNullByDefault({}) ManagedItemProvider itemProvider;
122 protected @NonNullByDefault({}) ManagedItemChannelLinkProvider itemChannelLinkProvider;
123 protected @NonNullByDefault({}) ItemRegistry itemRegistry;
124 protected @NonNullByDefault({}) CoreItemFactory coreItemFactory;
126 private Set<Item> addedItems = new HashSet<>();
127 private Set<Thing> addedThings = new HashSet<>();
128 private Set<ItemChannelLink> addedLinks = new HashSet<>();
129 private StateSubscriber stateSubscriber = new StateSubscriber();
131 protected @Mock @NonNullByDefault({}) ModbusCommunicationInterface comms;
133 public AbstractModbusOSGiTest() {
138 * Before each test, configure mocked services
141 public void setUpAbstractModbusOSGiTest() {
142 logger.debug("setUpAbstractModbusOSGiTest BEGIN");
143 registerVolatileStorageService();
144 registerService(mockedModbusManager);
145 registerService(stateSubscriber);
147 swapModbusManagerToMocked();
149 thingProvider = getService(ThingProvider.class, ManagedThingProvider.class);
150 assertThat("Could not get ManagedThingProvider", thingProvider, is(notNullValue()));
151 itemProvider = getService(ItemProvider.class, ManagedItemProvider.class);
152 assertThat("Could not get ManagedItemProvider", itemProvider, is(notNullValue()));
153 itemChannelLinkProvider = getService(ItemChannelLinkProvider.class, ManagedItemChannelLinkProvider.class);
154 assertThat("Could not get ManagedItemChannelLinkProvider", itemChannelLinkProvider, is(notNullValue()));
155 itemRegistry = getService(ItemRegistry.class);
156 assertThat("Could not get ItemRegistry", itemRegistry, is(notNullValue()));
158 coreItemFactory = new CoreItemFactory();
160 // Clean slate for all tests
161 reset(mockedModbusManager);
163 stateSubscriber.stateUpdates.clear();
164 logger.debug("setUpAbstractModbusOSGiTest END");
168 public void tearDownAbstractModbusOSGiTest() throws Exception {
169 logger.debug("tearDownAbstractModbusOSGiTest BEGIN");
170 swapModbusManagerToReal();
171 for (Item item : addedItems) {
172 assertNotNull(itemProvider.remove(item.getName()));
174 for (Thing thing : addedThings) {
177 for (ItemChannelLink link : addedLinks) {
178 logger.debug("Unlinking {} <-> {}", link.getItemName(), link.getLinkedUID());
179 assertNotNull(itemChannelLinkProvider.remove(link.getUID()));
181 logger.debug("tearDownAbstractModbusOSGiTest END");
184 protected void addThing(Thing thing) {
185 assertThat(addedThings.contains(thing), not(equalTo(true)));
186 ThingHandler mockHandler = thing.getHandler();
187 if (mockHandler != null) {
188 // If there is a handler attached to fresh thing, it should be mocked (this pattern is used with some tests)
189 assertThat(Mockito.mockingDetails(thing.getHandler()).isMock(), is(equalTo(true)));
192 thingProvider.add(thing);
193 waitForAssert(() -> assertThat(thing.getHandler(), notNullValue()));
194 assertThat(thing.getConfiguration(), is(notNullValue()));
195 addedThings.add(thing);
196 if (mockHandler != null) {
197 // Re-attach mock handler
198 ThingHandler realHandlerInitedByCore = thing.getHandler();
199 assertNotNull(realHandlerInitedByCore);
200 assertNotSame(realHandlerInitedByCore, mockHandler);
201 realHandlerInitedByCore.dispose();
202 thing.setHandler(mockHandler);
206 protected void disposeThing(Thing thing) {
207 thingProvider.remove(thing.getUID());
210 protected void addItem(Item item) {
211 assertThat(addedItems.contains(item), not(equalTo(true)));
212 itemProvider.add(item);
213 addedItems.add(item);
216 protected void linkItem(String itemName, ChannelUID channelUID) {
217 logger.debug("Linking {} <-> {}", itemName, channelUID);
218 ItemChannelLink link = new ItemChannelLink(itemName, channelUID);
219 assertThat(addedLinks.contains(link), not(equalTo(true)));
220 itemChannelLinkProvider.add(link);
221 addedLinks.add(link);
224 protected @Nullable List<State> getStateUpdates(String itemName) {
225 return stateSubscriber.stateUpdates.get(itemName);
228 protected void mockTransformation(String name, TransformationService service) {
229 Dictionary<String, Object> params = new Hashtable<>();
230 params.put("openhab.transform", name);
231 registerService(service, params);
234 protected void mockCommsToModbusManager() {
235 assert comms != null;
236 doReturn(comms).when(mockedModbusManager).newModbusCommunicationInterface(any(), any());
239 protected void swapModbusManagerToMocked() {
240 assertNull(realModbusManager);
241 realModbusManager = getService(ModbusManager.class);
242 assertThat("Could not get ModbusManager", realModbusManager, is(notNullValue()));
243 assertThat("Could not get ModbusManagerImpl", realModbusManager.getClass().getSimpleName(),
244 is(equalTo("ModbusManagerImpl")));
245 assertNotNull(realModbusManager);
247 ModbusHandlerFactory modbusHandlerFactory = getService(ThingHandlerFactory.class, ModbusHandlerFactory.class);
248 assertThat("Could not get ModbusHandlerFactory", modbusHandlerFactory, is(notNullValue()));
249 assertNotNull(modbusHandlerFactory);
250 modbusHandlerFactory.unsetModbusManager(realModbusManager);
251 modbusHandlerFactory.setModbusManager(mockedModbusManager);
254 protected void swapModbusManagerToReal() {
255 assertNotNull(realModbusManager);
256 ModbusHandlerFactory modbusHandlerFactory = getService(ThingHandlerFactory.class, ModbusHandlerFactory.class);
257 assertThat("Could not get ModbusHandlerFactory", modbusHandlerFactory, is(notNullValue()));
258 assertNotNull(modbusHandlerFactory);
259 modbusHandlerFactory.unsetModbusManager(mockedModbusManager);
260 modbusHandlerFactory.setModbusManager(realModbusManager);