]> git.basschouten.com Git - openhab-addons.git/blob
73d1bdfaab6befcd9b6eddc0a7466c0bf48a6a97
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.mqtt.generic.mapping;
14
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.*;
21
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;
30
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;
44
45 /**
46  * Tests cases for {@link org.openhab.binding.mqtt.generic.mapping.AbstractMqttAttributeClass}.
47  *
48  * <p>
49  * How it works:
50  *
51  * <ol>
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.
56  * </ol>
57  *
58  * @author David Graeff - Initial contribution
59  */
60 @ExtendWith(MockitoExtension.class)
61 @MockitoSettings(strictness = Strictness.WARN)
62 public class MqttTopicClassMapperTests {
63     @Retention(RetentionPolicy.RUNTIME)
64     @Target({ FIELD })
65     private @interface TestValue {
66         String value() default "";
67     }
68
69     @TopicPrefix
70     public static class Attributes extends AbstractMqttAttributeClass {
71         public transient String ignoreTransient = "";
72         public final String ignoreFinal = "";
73
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;
79
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;
83
84         public enum ReadyState {
85             unknown,
86             init,
87             ready,
88         }
89
90         public @TestValue("init") ReadyState state = ReadyState.unknown;
91
92         public enum DataTypeEnum {
93             unknown,
94             integer_,
95             float_,
96         }
97
98         public @TestValue("integer") @MQTTvalueTransform(suffix = "_") DataTypeEnum datatype = DataTypeEnum.unknown;
99
100         @Override
101         public @NonNull Object getFieldsOf() {
102             return this;
103         }
104     }
105
106     @Mock
107     MqttBrokerConnection connection;
108
109     @Mock
110     ScheduledExecutorService executor;
111
112     @Mock
113     AttributeChanged fieldChangedObserver;
114
115     @Spy
116     Object countInjectedFields = new Object();
117     int injectedFields = 0;
118
119     // A completed future is returned for a subscribe call to the attributes
120     final CompletableFuture<Boolean> future = CompletableFuture.completedFuture(true);
121
122     @BeforeEach
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();
128     }
129
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());
139         return s;
140     }
141
142     @Test
143     public void subscribeToCorrectFields() {
144         Attributes attributes = spy(new Attributes());
145
146         doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
147                 anyBoolean());
148
149         // Subscribe now to all fields
150         CompletableFuture<Void> future = attributes.subscribeAndReceive(connection, executor, "homie/device123", null,
151                 10);
152         assertThat(future.isDone(), is(true));
153         assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
154     }
155
156     // TODO timeout
157     @SuppressWarnings({ "null", "unused" })
158     @Test
159     public void subscribeAndReceive() throws IllegalArgumentException, IllegalAccessException {
160         final Attributes attributes = spy(new Attributes());
161
162         doAnswer(this::createSubscriberAnswer).when(attributes).createSubscriber(any(), any(), anyString(),
163                 anyBoolean());
164
165         verify(connection, times(0)).subscribe(anyString(), any());
166
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));
171
172         // We expect 10 subscriptions now
173         assertThat(attributes.subscriptions.size(), is(10 + injectedFields));
174
175         int loopCounter = 0;
176
177         // Assign each field the value of the test annotation via the processMessage method
178         for (SubscribeFieldToMQTTtopic f : attributes.subscriptions) {
179             @Nullable
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);
185                 continue;
186             }
187
188             verify(f).subscribeAndReceive(any(), anyInt());
189
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(),
193                     anyBoolean());
194
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));
203             } else {
204                 assertThat(Stream.of((String[]) f.field.get(attributes)).reduce((v, i) -> v + "," + i).orElse(""),
205                         is(annotation.value()));
206             }
207         }
208
209         assertThat(future.isDone(), is(true));
210     }
211 }