/
AbstractMqttClientActorTest.java
415 lines (340 loc) · 17.8 KB
/
AbstractMqttClientActorTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
* Copyright (c) 2019 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.services.connectivity.messaging.mqtt;
import static java.util.Collections.singleton;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.eclipse.ditto.model.connectivity.ConnectivityModelFactory.newTarget;
import static org.eclipse.ditto.services.connectivity.messaging.TestConstants.Authorization.AUTHORIZATION_CONTEXT;
import static org.eclipse.ditto.services.connectivity.messaging.TestConstants.disableLogging;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.connectivity.Connection;
import org.eclipse.ditto.model.connectivity.ConnectionId;
import org.eclipse.ditto.model.connectivity.ConnectionSignalIdEnforcementFailedException;
import org.eclipse.ditto.model.connectivity.ConnectionType;
import org.eclipse.ditto.model.connectivity.ConnectivityModelFactory;
import org.eclipse.ditto.model.connectivity.ConnectivityStatus;
import org.eclipse.ditto.model.connectivity.Source;
import org.eclipse.ditto.model.connectivity.Target;
import org.eclipse.ditto.model.connectivity.Topic;
import org.eclipse.ditto.services.connectivity.messaging.AbstractBaseClientActorTest;
import org.eclipse.ditto.services.connectivity.messaging.BaseClientState;
import org.eclipse.ditto.services.connectivity.messaging.TestConstants;
import org.eclipse.ditto.services.models.connectivity.OutboundSignal;
import org.eclipse.ditto.signals.commands.connectivity.exceptions.ConnectionFailedException;
import org.eclipse.ditto.signals.commands.connectivity.modify.CloseConnection;
import org.eclipse.ditto.signals.commands.connectivity.modify.OpenConnection;
import org.eclipse.ditto.signals.commands.connectivity.modify.TestConnection;
import org.eclipse.ditto.signals.commands.connectivity.query.RetrieveConnectionMetrics;
import org.eclipse.ditto.signals.commands.connectivity.query.RetrieveConnectionMetricsResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyThing;
import org.eclipse.ditto.signals.events.things.ThingModifiedEvent;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.actor.Status;
import akka.actor.Terminated;
import akka.stream.Attributes;
import akka.testkit.TestProbe;
import akka.testkit.javadsl.TestKit;
import scala.concurrent.duration.FiniteDuration;
public abstract class AbstractMqttClientActorTest<M> extends AbstractBaseClientActorTest {
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMqttClientActorTest.class);
protected static final Status.Success CONNECTED_SUCCESS = new Status.Success(BaseClientState.CONNECTED);
protected static final Status.Success DISCONNECTED_SUCCESS = new Status.Success(BaseClientState.DISCONNECTED);
private static final TestConstants.FreePort freePort = new TestConstants.FreePort();
private static final Target TARGET = newTarget("target", AUTHORIZATION_CONTEXT, null, 1, Topic.TWIN_EVENTS);
private static final String SOURCE_ADDRESS = "source";
private static final Source MQTT_SOURCE = ConnectivityModelFactory
.newSourceBuilder()
.authorizationContext(AUTHORIZATION_CONTEXT)
.index(1)
.consumerCount(1)
.address(SOURCE_ADDRESS)
.qos(1)
.build();
protected static ActorSystem actorSystem;
protected ConnectionId connectionId;
private String serverHost;
protected Connection connection;
@ClassRule
public static final MqttServerRule mqttServer = new MqttServerRule(freePort.getPort());
@BeforeClass
public static void setUp() {
actorSystem = ActorSystem.create("AkkaTestSystem", TestConstants.CONFIG);
}
@AfterClass
public static void tearDown() {
TestKit.shutdownActorSystem(actorSystem, scala.concurrent.duration.Duration.apply(5, TimeUnit.SECONDS),
false);
}
@Before
public void initializeConnection() {
connectionId = TestConstants.createRandomConnectionId();
serverHost = "tcp://localhost:" + freePort.getPort();
connection = ConnectivityModelFactory.newConnectionBuilder(connectionId, ConnectionType.MQTT,
ConnectivityStatus.OPEN, serverHost)
.sources(singletonList(MQTT_SOURCE))
.targets(singletonList(TARGET))
.failoverEnabled(true)
.build();
}
@Override
protected Connection getConnection() {
return connection;
}
@Override
protected ActorSystem getActorSystem() {
return actorSystem;
}
@Test
public void testConnect() {
new TestKit(actorSystem) {{
final Props props = createClientActor(getRef());
final ActorRef mqttClientActor = actorSystem.actorOf(props);
mqttClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), getRef());
expectMsg(CONNECTED_SUCCESS);
mqttClientActor.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), getRef());
expectMsg(DISCONNECTED_SUCCESS);
expectDisconnectCalled();
}};
}
@Test
public void testTestConnection() {
new TestKit(actorSystem) {{
final Props props = createClientActor(getRef());
final ActorRef mqttClientActor = watch(actorSystem.actorOf(props));
mqttClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
expectMsg(new Status.Success("successfully connected + initialized mapper"));
expectDisconnectCalled();
// client actor should be stopped after testing
fishForMessage(FiniteDuration.apply(5L, TimeUnit.SECONDS), "client actor should stop after test",
msg -> msg instanceof Terminated && ((Terminated) msg).getActor().equals(mqttClientActor));
expectDisconnectCalled();
}};
}
@Test
public void testTestConnectionFails() {
new TestKit(actorSystem) {{
final Props props = createFailingClientActor(getRef());
final ActorRef mqttClientActor = actorSystem.actorOf(props);
mqttClientActor.tell(TestConnection.of(connection, DittoHeaders.empty()), getRef());
final Status.Failure failure = expectMsgClass(Status.Failure.class);
assertThat(failure.cause()).isInstanceOf(ConnectionFailedException.class);
expectDisconnectCalled();
}};
}
@Test
public void testRetrieveConnectionMetrics() {
new TestKit(actorSystem) {{
final Source mqttSource = ConnectivityModelFactory.newSourceBuilder()
.authorizationContext(AUTHORIZATION_CONTEXT)
.index(2)
.consumerCount(1)
.address("topic1")
.address("topic2")
.qos(1)
.build();
final Connection connectionWithAdditionalSources = connection.toBuilder()
.sources(singletonList(mqttSource)).build();
final String modifyThing = TestConstants.modifyThing();
final Props props = createClientActorWithMessages(connectionWithAdditionalSources, getRef(),
singletonList(mqttMessage(SOURCE_ADDRESS, modifyThing)));
final ActorRef underTest = actorSystem.actorOf(props);
final TestProbe controlProbe = TestProbe.apply(actorSystem);
underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), controlProbe.ref());
LOGGER.info("Waiting for connected...");
controlProbe.expectMsg(CONNECTED_SUCCESS);
expectMsgClass(ModifyThing.class);
underTest.tell(RetrieveConnectionMetrics.of(connectionId, DittoHeaders.empty()), getRef());
final RetrieveConnectionMetricsResponse metricsResponse =
expectMsgClass(RetrieveConnectionMetricsResponse.class);
LOGGER.info("metrics: {}", metricsResponse);
}};
}
@Test
public void testConsumeFromTopic() {
testConsumeModifyThing(connection, SOURCE_ADDRESS)
.expectMsgClass(ModifyThing.class);
}
@Test
public void testConsumeFromTopicWithIdEnforcement() {
final Source mqttSource = newFilteredMqttSource(
"eclipse/{{ thing:namespace }}/{{ thing:name }}",
"eclipse/+/+");
final Connection connectionWithEnforcement =
ConnectivityModelFactory.newConnectionBuilder(connectionId, ConnectionType.MQTT,
ConnectivityStatus.OPEN,
serverHost)
.sources(singletonList(mqttSource))
.build();
testConsumeModifyThing(connectionWithEnforcement, "eclipse/ditto/thing")
.expectMsgClass(ModifyThing.class);
}
@Test
public void testConsumeFromTopicWithIdEnforcementExpectErrorResponse() {
disableLogging(actorSystem);
final Source mqttSource = newFilteredMqttSource(
"eclipse/{{ thing:namespace }}/{{ thing:name }}", // enforcement filter
"eclipse/+/+" // subscribed topic
);
final Connection connectionWithEnforcement =
ConnectivityModelFactory.newConnectionBuilder(connectionId, ConnectionType.MQTT,
ConnectivityStatus.OPEN,
serverHost)
.sources(singletonList(mqttSource))
.build();
final M message = testConsumeModifyThing(connectionWithEnforcement, "eclipse/invalid/address")
.expectMsgClass(getMessageClass());
assertThat(extractPayload(message)).contains(ConnectionSignalIdEnforcementFailedException.ERROR_CODE);
}
private TestKit testConsumeModifyThing(final Connection connection, final String publishTopic) {
return new TestKit(actorSystem) {{
final TestProbe controlProbe = TestProbe.apply(actorSystem);
final Props props = createClientActorWithMessages(connection, getRef(),
singletonList(mqttMessage(publishTopic, TestConstants.modifyThing())));
final ActorRef mqttClientActor = actorSystem.actorOf(props);
mqttClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(CONNECTED_SUCCESS);
}};
}
private static Source newFilteredMqttSource(final String filter, final String... sources) {
return ConnectivityModelFactory.newSourceBuilder()
.authorizationContext(AUTHORIZATION_CONTEXT)
.index(1)
.consumerCount(1)
.addresses(TestConstants.asSet(sources))
.enforcement(ConnectivityModelFactory.newSourceAddressEnforcement(filter))
.qos(1)
.build();
}
@Test
public void testConsumeMultipleSources() {
new TestKit(actorSystem) {{
final TestProbe controlProbe = TestProbe.apply(actorSystem);
final List<String> irrelevantTopics = Arrays.asList("irrelevant", "topics");
final String[] subscriptions =
new String[]{"A1", "A1", "A1", "B1", "B1", "B2", "B2", "C1", "C2", "C3"};
final List<M> mockMessages =
Stream.concat(irrelevantTopics.stream(), Arrays.stream(subscriptions))
.map(topic -> mqttMessage(topic, TestConstants.modifyThing()))
.collect(Collectors.toList());
final Connection multipleSources =
ConnectivityModelFactory.newConnectionBuilder(connectionId, ConnectionType.MQTT,
ConnectivityStatus.OPEN, serverHost)
.sources(Arrays.asList(
newMqttSource(3, 1, "A1"),
newMqttSource(2, 2, "B1", "B2"),
newMqttSource(1, 3, "C1", "C2", "C3"))
)
.build();
final ConnectionId connectionId = TestConstants.createRandomConnectionId();
final Props props = createClientActorWithMessages(multipleSources, getRef(), mockMessages);
final ActorRef underTest = actorSystem.actorOf(props);
underTest.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(CONNECTED_SUCCESS);
final List<String> receivedTopics = new LinkedList<>();
IntStream.range(0, subscriptions.length).forEach(i -> {
LOGGER.info("Consuming message {}", i);
final String topic = expectMsgClass(ModifyThing.class).getDittoHeaders().get("mqtt.topic");
LOGGER.info("Got message with topic {}", topic);
receivedTopics.add(topic);
});
underTest.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(DISCONNECTED_SUCCESS);
assertThat(receivedTopics).containsExactlyInAnyOrder(subscriptions);
}};
}
private static Source newMqttSource(final int consumerCount, final int index, final String... sources) {
return ConnectivityModelFactory.newSourceBuilder()
.authorizationContext(AUTHORIZATION_CONTEXT)
.index(index)
.consumerCount(consumerCount)
.addresses(TestConstants.asSet(sources))
.qos(1)
.build();
}
@Test
public void testReconnectAndConsumeFromTopic() throws InterruptedException {
new TestKit(actorSystem) {{
final TestProbe controlProbe = TestProbe.apply(actorSystem);
final Props props =
createClientActorWithMessages(connection, getRef(), singletonList(mqttMessage(SOURCE_ADDRESS,
TestConstants.modifyThing())));
final ActorRef mqttClientActor = actorSystem.actorOf(props);
mqttClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(CONNECTED_SUCCESS);
// ModifyThing automatically published by mock connection
expectMsgClass(ModifyThing.class);
mqttClientActor.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(DISCONNECTED_SUCCESS);
mqttClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(CONNECTED_SUCCESS);
// ModifyThing automatically published by mock connection
expectMsgClass(ModifyThing.class);
mqttClientActor.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(DISCONNECTED_SUCCESS);
}};
}
@Test
public void testPublishToTopic() {
new TestKit(actorSystem) {{
final TestProbe controlProbe = TestProbe.apply(actorSystem);
final Props props = createClientActor(getRef());
final ActorRef underTest = actorSystem.actorOf(props);
underTest.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(CONNECTED_SUCCESS);
final ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(singleton(""));
final String expectedJson = TestConstants.signalToDittoProtocolJsonString(thingModifiedEvent);
LOGGER.info("Sending thing modified message: {}", thingModifiedEvent);
final OutboundSignal.WithExternalMessage mappedSignal =
Mockito.mock(OutboundSignal.WithExternalMessage.class);
when(mappedSignal.getTargets()).thenReturn(singletonList(TARGET));
when(mappedSignal.getSource()).thenReturn(thingModifiedEvent);
underTest.tell(mappedSignal, getRef());
final M receivedMessage = expectMsgClass(getMessageClass());
assertThat(extractTopic(receivedMessage)).isEqualTo(TARGET.getAddress());
assertThat(extractPayload(receivedMessage)).isEqualTo(expectedJson);
underTest.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
controlProbe.expectMsg(DISCONNECTED_SUCCESS);
}};
}
protected abstract Props createFailingClientActor(final ActorRef testProbe);
protected abstract Props createClientActorWithMessages(
final Connection connection, final ActorRef testProbe,
final List<M> messages);
protected abstract M mqttMessage(final String topic, final String payload);
@Nullable
protected abstract String extractPayload(M message);
@Nullable
protected abstract String extractTopic(M message);
protected abstract Class<M> getMessageClass();
protected abstract void expectDisconnectCalled();
}