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.junit.Assert.*;
18 import static org.mockito.ArgumentMatchers.*;
19 import static org.mockito.Mockito.*;
21 import java.lang.annotation.Retention;
22 import java.lang.annotation.RetentionPolicy;
23 import java.lang.annotation.Target;
24 import java.lang.reflect.Field;
25 import java.math.BigDecimal;
26 import java.util.concurrent.CompletableFuture;
27 import java.util.concurrent.ScheduledExecutorService;
28 import java.util.stream.Stream;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.mockito.Mock;
35 import org.mockito.MockitoAnnotations;
36 import org.mockito.Spy;
37 import org.mockito.invocation.InvocationOnMock;
38 import org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass.AttributeChanged;
39 import org.openhab.core.io.transport.mqtt.MqttBrokerConnection;
42 * Tests cases for {@link org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass}.
48 * <li>A DTO (data transfer object) is defined, here it is {@link Attributes}, which extends
49 * {@link org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass}.
50 * <li>The createSubscriber method is mocked so that no real MQTTConnection interaction happens.
51 * <li>The subscribeAndReceive method is called.
54 * @author David Graeff - Initial contribution
56 public class MqttTopicClassMapperTests {
57 @Retention(RetentionPolicy.RUNTIME)
59 private @interface TestValue {
60 String value() default "";
64 public static class Attributes extends AbstractMqttAttributeClass {
65 public transient String ignoreTransient = "";
66 public final String ignoreFinal = "";
68 public @TestValue("string") String aString;
69 public @TestValue("false") Boolean aBoolean;
70 public @TestValue("10") Long aLong;
71 public @TestValue("10") Integer aInteger;
72 public @TestValue("10") BigDecimal aDecimal;
74 public @TestValue("10") @TopicPrefix("a") int Int = 24;
75 public @TestValue("false") boolean aBool = true;
76 public @TestValue("abc,def") @MQTTvalueTransform(splitCharacter = ",") String[] properties;
78 public enum ReadyState {
84 public @TestValue("init") ReadyState state = ReadyState.unknown;
86 public enum DataTypeEnum {
92 public @TestValue("integer") @MQTTvalueTransform(suffix = "_") DataTypeEnum datatype = DataTypeEnum.unknown;
95 public @NonNull Object getFieldsOf() {
101 MqttBrokerConnection connection;
104 ScheduledExecutorService executor;
107 AttributeChanged fieldChangedObserver;
110 Object countInjectedFields = new Object();
111 int injectedFields = 0;
113 // A completed future is returned for a subscribe call to the attributes
114 final CompletableFuture<Boolean> future = CompletableFuture.completedFuture(true);
117 public void setUp() {
118 MockitoAnnotations.initMocks(this);
119 doReturn(CompletableFuture.completedFuture(true)).when(connection).subscribe(any(), any());
120 doReturn(CompletableFuture.completedFuture(true)).when(connection).unsubscribe(any(), any());
121 injectedFields = (int) Stream.of(countInjectedFields.getClass().getDeclaredFields())
122 .filter(AbstractMqttAttributeClass::filterField).count();
125 public Object createSubscriberAnswer(InvocationOnMock invocation) {
126 final AbstractMqttAttributeClass attributes = (AbstractMqttAttributeClass) invocation.getMock();
127 final ScheduledExecutorService scheduler = (ScheduledExecutorService) invocation.getArguments()[0];
128 final Field field = (Field) invocation.getArguments()[1];
129 final String topic = (String) invocation.getArguments()[2];
130 final boolean mandatory = (boolean) invocation.getArguments()[3];
131 final SubscribeFieldToMQTTtopic s = spy(
132 new SubscribeFieldToMQTTtopic(scheduler, field, attributes, topic, mandatory));
133 doReturn(CompletableFuture.completedFuture(true)).when(s).subscribeAndReceive(any(), anyInt());
138 public void subscribeToCorrectFields() {
139 Attributes attributes = spy(new Attributes());
141 doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
144 // Subscribe now to all fields
145 CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123", null,
147 assertThat(future.isDone(), is(true));
148 assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
152 @SuppressWarnings({ "null", "unused" })
154 public void subscribeAndReceive() throws IllegalArgumentException, IllegalAccessException {
155 final Attributes attributes = spy(new Attributes());
157 doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
160 verify(connection, times(0)).subscribe(anyString(), any());
162 // Subscribe now to all fields
163 CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123",
164 fieldChangedObserver, 10);
165 assertThat(future.isDone(), is(true));
167 // We expect 10 subscriptions now
168 assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
172 // Assign each field the value of the test annotation via the processMessage method
173 for (SubscribeFieldToMQTTtopic f : attributes.subscriptions) {
175 TestValue annotation = f.field.getAnnotation(TestValue.class);
176 // A non-annotated field means a Mockito injected field.
177 // Ignore that and complete the corresponding future.
178 if (annotation == null) {
179 f.future.complete(null);
183 verify(f).subscribeAndReceive(any(), anyInt());
185 // Simulate a received MQTT value and use the annotation data as input.
186 f.processMessage(f.topic, annotation.value().getBytes());
187 verify(fieldChangedObserver, times(++loopCounter)).attributeChanged(any(), any(), any(), any(),
190 // Check each value if the assignment worked
191 if (!f.field.getType().isArray()) {
192 assertNotNull(f.field.getName() + " is null", f.field.get(attributes));
193 // Consider if a mapToField was used that would manipulate the received value
194 MQTTvalueTransform mapToField = f.field.getAnnotation(MQTTvalueTransform.class);
195 String prefix = mapToField != null ? mapToField.prefix() : "";
196 String suffix = mapToField != null ? mapToField.suffix() : "";
197 assertThat(f.field.get(attributes).toString(), is(prefix + annotation.value() + suffix));
199 assertThat(Stream.of((String[]) f.field.get(attributes)).reduce((v, i) -> v + "," + i).orElse(""),
200 is(annotation.value()));
204 assertThat(future.isDone(), is(true));