2 * Copyright (c) 2010-2020 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.mqtt.generic.mapping;
15 import static java.lang.annotation.ElementType.FIELD;
16 import static org.hamcrest.CoreMatchers.is;
17 import static org.hamcrest.MatcherAssert.assertThat;
18 import static org.junit.jupiter.api.Assertions.assertNotNull;
19 import static org.mockito.ArgumentMatchers.*;
20 import static org.mockito.Mockito.*;
22 import java.lang.annotation.Retention;
23 import java.lang.annotation.RetentionPolicy;
24 import java.lang.annotation.Target;
25 import java.lang.reflect.Field;
26 import java.math.BigDecimal;
27 import java.util.concurrent.CompletableFuture;
28 import java.util.concurrent.ScheduledExecutorService;
29 import java.util.stream.Stream;
31 import org.eclipse.jdt.annotation.NonNull;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.junit.jupiter.api.BeforeEach;
34 import org.junit.jupiter.api.Test;
35 import org.junit.jupiter.api.extension.ExtendWith;
36 import org.mockito.Mock;
37 import org.mockito.Spy;
38 import org.mockito.invocation.InvocationOnMock;
39 import org.mockito.junit.jupiter.MockitoExtension;
40 import org.mockito.junit.jupiter.MockitoSettings;
41 import org.mockito.quality.Strictness;
42 import org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass.AttributeChanged;
43 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
46 * Tests cases for {@link org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass}.
52 * <li>A DTO (data transfer object) is defined, here it is {@link Attributes}, which extends
53 * {@link org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass}.
54 * <li>The createSubscriber method is mocked so that no real MQTTConnection interaction happens.
55 * <li>The subscribeAndReceive method is called.
58 * @author David Graeff - Initial contribution
60 @ExtendWith(MockitoExtension.class)
61 @MockitoSettings(strictness = Strictness.WARN)
62 public class MqttTopicClassMapperTests {
63 @Retention(RetentionPolicy.RUNTIME)
65 private @interface TestValue {
66 String value() default "";
70 public static class Attributes extends AbstractMqttAttributeClass {
71 public transient String ignoreTransient = "";
72 public final String ignoreFinal = "";
74 public @TestValue("string") String aString;
75 public @TestValue("false") Boolean aBoolean;
76 public @TestValue("10") Long aLong;
77 public @TestValue("10") Integer aInteger;
78 public @TestValue("10") BigDecimal aDecimal;
80 public @TestValue("10") @TopicPrefix("a") int Int = 24;
81 public @TestValue("false") boolean aBool = true;
82 public @TestValue("abc,def") @MQTTvalueTransform(splitCharacter = ",") String[] properties;
84 public enum ReadyState {
90 public @TestValue("init") ReadyState state = ReadyState.unknown;
92 public enum DataTypeEnum {
98 public @TestValue("integer") @MQTTvalueTransform(suffix = "_") DataTypeEnum datatype = DataTypeEnum.unknown;
101 public @NonNull Object getFieldsOf() {
107 MqttBrokerConnection connection;
110 ScheduledExecutorService executor;
113 AttributeChanged fieldChangedObserver;
116 Object countInjectedFields = new Object();
117 int injectedFields = 0;
119 // A completed future is returned for a subscribe call to the attributes
120 final CompletableFuture<Boolean> future = CompletableFuture.completedFuture(true);
123 public void setUp() {
124 doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
125 doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
126 injectedFields = (int) Stream.of(countInjectedFields.getClass().getDeclaredFields())
127 .filter(AbstractMqttAttributeClass::filterField).count();
130 public Object createSubscriberAnswer(InvocationOnMock invocation) {
131 final AbstractMqttAttributeClass attributes = (AbstractMqttAttributeClass) invocation.getMock();
132 final ScheduledExecutorService scheduler = (ScheduledExecutorService) invocation.getArguments()[0];
133 final Field field = (Field) invocation.getArguments()[1];
134 final String topic = (String) invocation.getArguments()[2];
135 final boolean mandatory = (boolean) invocation.getArguments()[3];
136 final SubscribeFieldToMQTTtopic s = spy(
137 new SubscribeFieldToMQTTtopic(scheduler, field, attributes, topic, mandatory));
138 doReturn(CompletableFuture.completedFuture(true)).when(s).subscribeAndReceive(any(), anyInt());
143 public void subscribeToCorrectFields() {
144 Attributes attributes = spy(new Attributes());
146 doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
149 // Subscribe now to all fields
150 CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123", null,
152 assertThat(future.isDone(), is(true));
153 assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
157 @SuppressWarnings({ "null", "unused" })
159 public void subscribeAndReceive() throws IllegalArgumentException, IllegalAccessException {
160 final Attributes attributes = spy(new Attributes());
162 doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
165 verify(connection, times(0)).subscribe(anyString(), any());
167 // Subscribe now to all fields
168 CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123",
169 fieldChangedObserver, 10);
170 assertThat(future.isDone(), is(true));
172 // We expect 10 subscriptions now
173 assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
177 // Assign each field the value of the test annotation via the processMessage method
178 for (SubscribeFieldToMQTTtopic f : attributes.subscriptions) {
180 TestValue annotation = f.field.getAnnotation(TestValue.class);
181 // A non-annotated field means a Mockito injected field.
182 // Ignore that and complete the corresponding future.
183 if (annotation == null) {
184 f.future.complete(null);
188 verify(f).subscribeAndReceive(any(), anyInt());
190 // Simulate a received MQTT value and use the annotation data as input.
191 f.processMessage(f.topic, annotation.value().getBytes());
192 verify(fieldChangedObserver, times(++loopCounter)).attributeChanged(any(), any(), any(), any(),
195 // Check each value if the assignment worked
196 if (!f.field.getType().isArray()) {
197 assertNotNull(f.field.get(attributes), f.field.getName() + " is null");
198 // Consider if a mapToField was used that would manipulate the received value
199 MQTTvalueTransform mapToField = f.field.getAnnotation(MQTTvalueTransform.class);
200 String prefix = mapToField != null ? mapToField.prefix() : "";
201 String suffix = mapToField != null ? mapToField.suffix() : "";
202 assertThat(f.field.get(attributes).toString(), is(prefix + annotation.value() + suffix));
204 assertThat(Stream.of((String[]) f.field.get(attributes)).reduce((v, i) -> v + "," + i).orElse(""),
205 is(annotation.value()));
209 assertThat(future.isDone(), is(true));