forked from eclipse-paho/paho.mqtt.python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_mqttv5.py
1368 lines (1149 loc) · 56.1 KB
/
test_mqttv5.py
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
*******************************************************************
Copyright (c) 2013, 2019 IBM Corp.
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v2.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Ian Craggs - initial implementation and/or documentation
*******************************************************************
"""
import getopt
import logging
import sys
import threading
import time
import traceback
import unittest
import paho.mqtt
import paho.mqtt.client
from paho.mqtt.packettypes import PacketTypes
from paho.mqtt.properties import Properties
from paho.mqtt.reasoncodes import ReasonCodes
from paho.mqtt.subscribeoptions import SubscribeOptions
class Callbacks:
def __init__(self):
self.messages = []
self.publisheds = []
self.subscribeds = []
self.unsubscribeds = []
self.disconnecteds = []
self.connecteds = []
self.conn_failures = []
def __str__(self):
return str(self.messages) + str(self.messagedicts) + str(self.publisheds) + \
str(self.subscribeds) + \
str(self.unsubscribeds) + str(self.disconnects)
def clear(self):
self.__init__()
def on_connect(self, client, userdata, flags, reasonCode, properties):
self.connecteds.append({"userdata": userdata, "flags": flags,
"reasonCode": reasonCode, "properties": properties})
def on_connect_fail(self, client, userdata):
self.conn_failures.append({"userdata": userdata})
def wait(self, alist, timeout=2):
interval = 0.2
total = 0
while len(alist) == 0 and total < timeout:
time.sleep(interval)
total += interval
return alist.pop(0) # if len(alist) > 0 else None
def wait_connect_fail(self):
return self.wait(self.conn_failures, timeout=10)
def wait_connected(self):
return self.wait(self.connecteds)
def on_disconnect(self, client, userdata, reasonCode, properties=None):
self.disconnecteds.append(
{"reasonCode": reasonCode, "properties": properties})
def wait_disconnected(self):
return self.wait(self.disconnecteds)
def on_message(self, client, userdata, message):
self.messages.append({"userdata": userdata, "message": message})
def published(self, client, userdata, msgid):
self.publisheds.append(msgid)
def wait_published(self):
return self.wait(self.publisheds)
def on_subscribe(self, client, userdata, mid, reasonCodes, properties):
self.subscribeds.append({"mid": mid, "userdata": userdata,
"properties": properties, "reasonCodes": reasonCodes})
def wait_subscribed(self):
return self.wait(self.subscribeds)
def unsubscribed(self, client, userdata, mid, properties, reasonCodes):
self.unsubscribeds.append({"mid": mid, "userdata": userdata,
"properties": properties, "reasonCodes": reasonCodes})
def wait_unsubscribed(self):
return self.wait(self.unsubscribeds)
def on_log(self, client, userdata, level, buf):
print(buf)
def register(self, client):
client.on_connect = self.on_connect
client.on_subscribe = self.on_subscribe
client.on_publish = self.published
client.on_unsubscribe = self.unsubscribed
client.on_message = self.on_message
client.on_disconnect = self.on_disconnect
client.on_connect_fail = self.on_connect_fail
client.on_log = self.on_log
def cleanRetained(port):
callback = Callbacks()
curclient = paho.mqtt.client.Client("clean retained".encode("utf-8"),
protocol=paho.mqtt.client.MQTTv5)
curclient.loop_start()
callback.register(curclient)
curclient.connect(host="localhost", port=port)
response = callback.wait_connected()
curclient.subscribe("#", options=SubscribeOptions(qos=0))
response = callback.wait_subscribed() # wait for retained messages to arrive
time.sleep(1)
for message in callback.messages:
logging.info("deleting retained message for topic", message["message"])
curclient.publish(message["message"].topic, b"", 0, retain=True)
curclient.disconnect()
curclient.loop_stop()
time.sleep(.1)
def cleanup(port):
# clean all client state
print("clean up starting")
clientids = ("aclient", "bclient")
for clientid in clientids:
curclient = paho.mqtt.client.Client(clientid.encode(
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
curclient.loop_start()
curclient.connect(host="localhost", port=port, clean_start=True)
time.sleep(.1)
curclient.disconnect()
time.sleep(.1)
curclient.loop_stop()
# clean retained messages
cleanRetained(port)
print("clean up finished")
class Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
global callback, callback2, aclient, bclient
sys.path.append("paho.mqtt.testing/interoperability/")
try:
import mqtt.brokers
except ImportError:
raise unittest.SkipTest("paho.mqtt.testing not present.")
cls._test_broker = threading.Thread(
target=mqtt.brokers.run,
kwargs={
"config": ["listener 0"],
},
)
cls._test_broker.daemon = True
cls._test_broker.start()
# Wait a bit for TCP server to bind to an address
time.sleep(0.5)
# Hack to find the port used by the test broker...
cls._test_broker_port = mqtt.brokers.listeners.TCPListeners.server.socket.getsockname()[1]
setData()
cleanup(cls._test_broker_port)
callback = Callbacks()
callback2 = Callbacks()
#aclient = mqtt_client.Client(b"\xEF\xBB\xBF" + "myclientid".encode("utf-8"))
#aclient = mqtt_client.Client("myclientid".encode("utf-8"))
aclient = paho.mqtt.client.Client("aclient".encode(
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
callback.register(aclient)
bclient = paho.mqtt.client.Client("bclient".encode(
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
callback2.register(bclient)
@classmethod
def tearDownClass(cls):
# Another hack to stop the test broker... we rely on fact that it use a sockserver.TCPServer
import mqtt.brokers
mqtt.brokers.listeners.TCPListeners.server.shutdown()
cls._test_broker.join(5)
def waitfor(self, queue, depth, limit):
total = 0
while len(queue) < depth and total < limit:
interval = .5
total += interval
time.sleep(interval)
def test_basic(self):
aclient.connect(host="localhost", port=self._test_broker_port)
aclient.loop_start()
response = callback.wait_connected()
self.assertEqual(response["reasonCode"].getName(), "Success")
aclient.subscribe(topics[0], options=SubscribeOptions(qos=2))
response = callback.wait_subscribed()
self.assertEqual(response["reasonCodes"][0].getName(), "Granted QoS 2")
aclient.publish(topics[0], b"qos 0")
aclient.publish(topics[0], b"qos 1", 1)
aclient.publish(topics[0], b"qos 2", 2)
i = 0
while len(callback.messages) < 3 and i < 10:
time.sleep(.2)
i += 1
self.assertEqual(len(callback.messages), 3)
aclient.disconnect()
callback.clear()
aclient.loop_stop()
def test_connect_fail(self):
clientid = "connection failure"
fclient, fcallback = self.new_client(clientid)
fclient.user_data_set(1)
fclient.connect_async("localhost", 1)
response = fcallback.wait_connect_fail()
self.assertEqual(response["userdata"], 1)
fclient.loop_stop()
def test_retained_message(self):
qos0topic = "fromb/qos 0"
qos1topic = "fromb/qos 1"
qos2topic = "fromb/qos2"
wildcardtopic = "fromb/+"
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.UserProperty = ("a", "2")
publish_properties.UserProperty = ("c", "3")
# retained messages
callback.clear()
aclient.connect(host="localhost", port=self._test_broker_port)
aclient.loop_start()
response = callback.wait_connected()
aclient.publish(topics[1], b"qos 0", 0,
retain=True, properties=publish_properties)
aclient.publish(topics[2], b"qos 1", 1,
retain=True, properties=publish_properties)
aclient.publish(topics[3], b"qos 2", 2,
retain=True, properties=publish_properties)
# wait until those messages are published
time.sleep(1)
aclient.subscribe(wildtopics[5], options=SubscribeOptions(qos=2))
response = callback.wait_subscribed()
self.assertEqual(response["reasonCodes"][0].getName(), "Granted QoS 2")
time.sleep(1)
aclient.disconnect()
aclient.loop_stop()
self.assertEqual(len(callback.messages), 3)
userprops = callback.messages[0]["message"].properties.UserProperty
self.assertTrue(userprops in [[("a", "2"), ("c", "3")], [
("c", "3"), ("a", "2")]], userprops)
userprops = callback.messages[1]["message"].properties.UserProperty
self.assertTrue(userprops in [[("a", "2"), ("c", "3")], [
("c", "3"), ("a", "2")]], userprops)
userprops = callback.messages[2]["message"].properties.UserProperty
self.assertTrue(userprops in [[("a", "2"), ("c", "3")], [
("c", "3"), ("a", "2")]], userprops)
qoss = [callback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
cleanRetained(self._test_broker_port)
def test_will_message(self):
# will messages and keep alive
callback.clear()
callback2.clear()
self.assertEqual(len(callback2.messages), 0, callback2.messages)
will_properties = Properties(PacketTypes.WILLMESSAGE)
will_properties.WillDelayInterval = 0 # this is the default anyway
will_properties.UserProperty = ("a", "2")
will_properties.UserProperty = ("c", "3")
aclient.will_set(topics[2], payload=b"will message",
properties=will_properties)
aclient.connect(host="localhost", port=self._test_broker_port, keepalive=2)
aclient.loop_start()
response = callback.wait_connected()
bclient.connect(host="localhost", port=self._test_broker_port)
bclient.loop_start()
response = callback2.wait_connected()
bclient.subscribe(topics[2], qos=2)
response = callback2.wait_subscribed()
self.assertEqual(response["reasonCodes"][0].getName(), "Granted QoS 2")
# keep alive timeout ought to be triggered so the will message is received
aclient.loop_stop() # so that pings aren't sent
self.waitfor(callback2.messages, 1, 10)
bclient.disconnect()
bclient.loop_stop()
# should have the will message
self.assertEqual(len(callback2.messages), 1, callback2.messages)
props = callback2.messages[0]["message"].properties
self.assertEqual(props.UserProperty, [("a", "2"), ("c", "3")])
def test_zero_length_clientid(self):
logging.info("Zero length clientid test starting")
callback0 = Callbacks()
client0 = paho.mqtt.client.Client(protocol=paho.mqtt.client.MQTTv5)
callback0.register(client0)
client0.loop_start()
# should not be rejected
client0.connect(host="localhost", port=self._test_broker_port, clean_start=False)
response = callback0.wait_connected()
self.assertEqual(response["reasonCode"].getName(), "Success")
self.assertTrue(
len(response["properties"].AssignedClientIdentifier) > 0)
client0.disconnect()
client0.loop_stop()
client0 = paho.mqtt.client.Client(protocol=paho.mqtt.client.MQTTv5)
callback0.register(client0)
client0.loop_start()
client0.connect(host="localhost", port=self._test_broker_port) # should work
response = callback0.wait_connected()
self.assertEqual(response["reasonCode"].getName(), "Success")
self.assertTrue(
len(response["properties"].AssignedClientIdentifier) > 0)
client0.disconnect()
client0.loop_stop()
# when we supply a client id, we should not get one assigned
client0 = paho.mqtt.client.Client(
"client0", protocol=paho.mqtt.client.MQTTv5)
callback0.register(client0)
client0.loop_start()
client0.connect(host="localhost", port=self._test_broker_port) # should work
response = callback0.wait_connected()
self.assertEqual(response["reasonCode"].getName(), "Success")
self.assertFalse(
hasattr(response["properties"], "AssignedClientIdentifier"))
client0.disconnect()
client0.loop_stop()
def test_offline_message_queueing(self):
# message queueing for offline clients
cleanRetained(self._test_broker_port)
ocallback = Callbacks()
clientid = "offline message queueing".encode("utf-8")
oclient = paho.mqtt.client.Client(
clientid, protocol=paho.mqtt.client.MQTTv5)
ocallback.register(oclient)
connect_properties = Properties(PacketTypes.CONNECT)
connect_properties.SessionExpiryInterval = 99999
oclient.loop_start()
oclient.connect(host="localhost", port=self._test_broker_port, properties=connect_properties)
response = ocallback.wait_connected()
oclient.subscribe(wildtopics[5], qos=2)
response = ocallback.wait_subscribed()
oclient.disconnect()
oclient.loop_stop()
bclient.loop_start()
bclient.connect(host="localhost", port=self._test_broker_port)
response = callback2.wait_connected()
bclient.publish(topics[1], b"qos 0", 0)
bclient.publish(topics[2], b"qos 1", 1)
bclient.publish(topics[3], b"qos 2", 2)
time.sleep(2)
bclient.disconnect()
bclient.loop_stop()
oclient = paho.mqtt.client.Client(
clientid, protocol=paho.mqtt.client.MQTTv5)
ocallback.register(oclient)
oclient.loop_start()
oclient.connect(host="localhost", port=self._test_broker_port, clean_start=False)
response = ocallback.wait_connected()
time.sleep(2)
oclient.disconnect()
oclient.loop_stop()
self.assertTrue(len(ocallback.messages) in [
2, 3], len(ocallback.messages))
logging.info("This server %s queueing QoS 0 messages for offline clients" %
("is" if len(ocallback.messages) == 3 else "is not"))
def test_overlapping_subscriptions(self):
# overlapping subscriptions. When there is more than one matching subscription for the same client for a topic,
# the server may send back one message with the highest QoS of any matching subscription, or one message for
# each subscription with a matching QoS.
ocallback = Callbacks()
clientid = "overlapping subscriptions".encode("utf-8")
oclient = paho.mqtt.client.Client(
clientid, protocol=paho.mqtt.client.MQTTv5)
ocallback.register(oclient)
oclient.loop_start()
oclient.connect(host="localhost", port=self._test_broker_port)
ocallback.wait_connected()
oclient.subscribe([(wildtopics[6], SubscribeOptions(qos=2)),
(wildtopics[0], SubscribeOptions(qos=1))])
ocallback.wait_subscribed()
oclient.publish(topics[3], b"overlapping topic filters", 2)
ocallback.wait_published()
time.sleep(1)
self.assertTrue(len(ocallback.messages) in [1, 2], ocallback.messages)
if len(ocallback.messages) == 1:
logging.info(
"This server is publishing one message for all matching overlapping subscriptions, not one for each.")
self.assertEqual(
ocallback.messages[0]["message"].qos, 2, ocallback.messages[0]["message"].qos)
else:
logging.info(
"This server is publishing one message per each matching overlapping subscription.")
self.assertTrue((ocallback.messages[0]["message"].qos == 2 and ocallback.messages[1]["message"].qos == 1) or
(ocallback.messages[0]["message"].qos == 1 and ocallback.messages[1]["message"].qos == 2), callback.messages)
oclient.disconnect()
oclient.loop_stop()
ocallback.clear()
def test_subscribe_failure(self):
# Subscribe failure. A new feature of MQTT 3.1.1 is the ability to send back negative reponses to subscribe
# requests. One way of doing this is to subscribe to a topic which is not allowed to be subscribed to.
logging.info("Subscribe failure test starting")
ocallback = Callbacks()
clientid = "subscribe failure".encode("utf-8")
oclient = paho.mqtt.client.Client(
clientid, protocol=paho.mqtt.client.MQTTv5)
ocallback.register(oclient)
oclient.loop_start()
oclient.connect(host="localhost", port=self._test_broker_port)
ocallback.wait_connected()
oclient.subscribe(nosubscribe_topics[0], qos=2)
response = ocallback.wait_subscribed()
self.assertEqual(response["reasonCodes"][0].getName(), "Unspecified error",
"return code should be 0x80 %s" % response["reasonCodes"][0].getName())
oclient.disconnect()
oclient.loop_stop()
def test_unsubscribe(self):
callback2.clear()
bclient.connect(host="localhost", port=self._test_broker_port)
bclient.loop_start()
callback2.wait_connected()
bclient.subscribe(topics[0], qos=2)
callback2.wait_subscribed()
bclient.subscribe(topics[1], qos=2)
callback2.wait_subscribed()
bclient.subscribe(topics[2], qos=2)
callback2.wait_subscribed()
time.sleep(1) # wait for any retained messages, hopefully
# Unsubscribe from one topic
bclient.unsubscribe(topics[0])
callback2.wait_unsubscribed()
callback2.clear() # if there were any retained messsages
aclient.connect(host="localhost", port=self._test_broker_port)
aclient.loop_start()
callback.wait_connected()
aclient.publish(topics[0], b"topic 0 - unsubscribed", 1, retain=False)
aclient.publish(topics[1], b"topic 1", 1, retain=False)
aclient.publish(topics[2], b"topic 2", 1, retain=False)
time.sleep(2)
bclient.disconnect()
bclient.loop_stop()
aclient.disconnect()
aclient.loop_stop()
self.assertEqual(len(callback2.messages), 2, callback2.messages)
def new_client(self, clientid):
callback = Callbacks()
client = paho.mqtt.client.Client(clientid.encode(
"utf-8"), protocol=paho.mqtt.client.MQTTv5)
callback.register(client)
client.loop_start()
return client, callback
def test_session_expiry(self):
# no session expiry property == never expire
connect_properties = Properties(PacketTypes.CONNECT)
connect_properties.SessionExpiryInterval = 0 # expire immediately
clientid = "session expiry"
eclient, ecallback = self.new_client(clientid)
eclient.connect(host="localhost", port=self._test_broker_port, properties=connect_properties)
connack = ecallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], False)
eclient.subscribe(topics[0], qos=2)
ecallback.wait_subscribed()
eclient.disconnect()
ecallback.wait_disconnected()
eclient.loop_stop()
fclient, fcallback = self.new_client(clientid)
# session should immediately expire
fclient.connect_async(host="localhost", port=self._test_broker_port, clean_start=False,
properties=connect_properties)
connack = fcallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], False)
fclient.disconnect()
fcallback.wait_disconnected()
connect_properties.SessionExpiryInterval = 5
eclient, ecallback = self.new_client(clientid)
eclient.connect(host="localhost", port=self._test_broker_port, properties=connect_properties)
connack = ecallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], False)
eclient.subscribe(topics[0], qos=2)
ecallback.wait_subscribed()
eclient.disconnect()
ecallback.wait_disconnected()
eclient.loop_stop()
time.sleep(2)
# session should still exist
fclient, fcallback = self.new_client(clientid)
fclient.connect(host="localhost", port=self._test_broker_port, clean_start=False,
properties=connect_properties)
connack = fcallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], True)
fclient.disconnect()
fcallback.wait_disconnected()
fclient.loop_stop()
time.sleep(6)
# session should not exist
fclient, fcallback = self.new_client(clientid)
fclient.connect(host="localhost", port=self._test_broker_port, clean_start=False,
properties=connect_properties)
connack = fcallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], False)
fclient.disconnect()
fcallback.wait_disconnected()
fclient.loop_stop()
eclient, ecallback = self.new_client(clientid)
connect_properties.SessionExpiryInterval = 1
connack = eclient.connect(
host="localhost", port=self._test_broker_port, properties=connect_properties)
connack = ecallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], False)
eclient.subscribe(topics[0], qos=2)
ecallback.wait_subscribed()
disconnect_properties = Properties(PacketTypes.DISCONNECT)
disconnect_properties.SessionExpiryInterval = 5
eclient.disconnect(properties=disconnect_properties)
ecallback.wait_disconnected()
eclient.loop_stop()
time.sleep(3)
# session should still exist as we changed the expiry interval on disconnect
fclient, fcallback = self.new_client(clientid)
fclient.connect(host="localhost", port=self._test_broker_port, clean_start=False,
properties=connect_properties)
connack = fcallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], True)
disconnect_properties.SessionExpiryInterval = 0
fclient.disconnect(properties=disconnect_properties)
fcallback.wait_disconnected()
fclient.loop_stop()
# session should immediately expire
fclient, fcallback = self.new_client(clientid)
fclient.connect(host="localhost", port=self._test_broker_port, clean_start=False,
properties=connect_properties)
connack = fcallback.wait_connected()
self.assertEqual(connack["reasonCode"].getName(), "Success")
self.assertEqual(connack["flags"]["session present"], False)
fclient.disconnect()
fcallback.wait_disconnected()
fclient.loop_stop()
fclient.loop_stop()
eclient.loop_stop()
def test_user_properties(self):
clientid = "user properties"
uclient, ucallback = self.new_client(clientid)
uclient.loop_start()
uclient.connect(host="localhost", port=self._test_broker_port)
ucallback.wait_connected()
uclient.subscribe(topics[0], qos=2)
ucallback.wait_subscribed()
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.UserProperty = ("a", "2")
publish_properties.UserProperty = ("c", "3")
uclient.publish(topics[0], b"", 0, retain=False,
properties=publish_properties)
uclient.publish(topics[0], b"", 1, retain=False,
properties=publish_properties)
uclient.publish(topics[0], b"", 2, retain=False,
properties=publish_properties)
count = 0
while len(ucallback.messages) < 3 and count < 50:
time.sleep(.1)
count += 1
uclient.disconnect()
ucallback.wait_disconnected()
uclient.loop_stop()
self.assertEqual(len(ucallback.messages), 3, ucallback.messages)
userprops = ucallback.messages[0]["message"].properties.UserProperty
self.assertTrue(userprops in [[("a", "2"), ("c", "3")], [
("c", "3"), ("a", "2")]], userprops)
userprops = ucallback.messages[1]["message"].properties.UserProperty
self.assertTrue(userprops in [[("a", "2"), ("c", "3")], [
("c", "3"), ("a", "2")]], userprops)
userprops = ucallback.messages[2]["message"].properties.UserProperty
self.assertTrue(userprops in [[("a", "2"), ("c", "3")], [
("c", "3"), ("a", "2")]], userprops)
qoss = [ucallback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
def test_payload_format(self):
clientid = "payload format"
pclient, pcallback = self.new_client(clientid)
pclient.loop_start()
pclient.connect_async(host="localhost", port=self._test_broker_port)
response = pcallback.wait_connected()
pclient.subscribe(topics[0], qos=2)
response = pcallback.wait_subscribed()
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.PayloadFormatIndicator = 1
publish_properties.ContentType = "My name"
info = pclient.publish(
topics[0], b"qos 0", 0, retain=False, properties=publish_properties)
info.wait_for_publish()
info = pclient.publish(
topics[0], b"qos 1", 1, retain=False, properties=publish_properties)
info.wait_for_publish()
info = pclient.publish(
topics[0], b"qos 2", 2, retain=False, properties=publish_properties)
info.wait_for_publish()
count = 0
while len(pcallback.messages) < 3 and count < 50:
time.sleep(.1)
count += 1
pclient.disconnect()
pcallback.wait_disconnected()
pclient.loop_stop()
self.assertEqual(len(pcallback.messages), 3, pcallback.messages)
props = pcallback.messages[0]["message"].properties
self.assertEqual(props.ContentType, "My name", props.ContentType)
self.assertEqual(props.PayloadFormatIndicator,
1, props.PayloadFormatIndicator)
props = pcallback.messages[1]["message"].properties
self.assertEqual(props.ContentType, "My name", props.ContentType)
self.assertEqual(props.PayloadFormatIndicator,
1, props.PayloadFormatIndicator)
props = pcallback.messages[2]["message"].properties
self.assertEqual(props.ContentType, "My name", props.ContentType)
self.assertEqual(props.PayloadFormatIndicator,
1, props.PayloadFormatIndicator)
qoss = [pcallback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
def test_message_expiry(self):
clientid = "message expiry"
connect_properties = Properties(PacketTypes.CONNECT)
connect_properties.SessionExpiryInterval = 99999
lbclient, lbcallback = self.new_client(clientid+" b")
lbclient.loop_start()
lbclient.connect(host="localhost", port=self._test_broker_port, properties=connect_properties)
response = lbcallback.wait_connected()
lbclient.subscribe(topics[0], qos=2)
response = lbcallback.wait_subscribed()
disconnect_properties = Properties(PacketTypes.DISCONNECT)
disconnect_properties.SessionExpiryInterval = 999999999
lbclient.disconnect(properties=disconnect_properties)
lbcallback.wait_disconnected()
lbclient.loop_stop()
laclient, lacallback = self.new_client(clientid+" a")
laclient.loop_start()
laclient.connect(host="localhost", port=self._test_broker_port)
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.MessageExpiryInterval = 1
laclient.publish(topics[0], b"qos 1 - expire", 1,
retain=False, properties=publish_properties)
laclient.publish(topics[0], b"qos 2 - expire", 2,
retain=False, properties=publish_properties)
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.MessageExpiryInterval = 6
laclient.publish(topics[0], b"qos 1 - don't expire",
1, retain=False, properties=publish_properties)
laclient.publish(topics[0], b"qos 2 - don't expire",
2, retain=False, properties=publish_properties)
time.sleep(3)
lbclient, lbcallback = self.new_client(clientid+" b")
lbclient.loop_start()
lbclient.connect(host="localhost", port=self._test_broker_port, clean_start=False)
lbcallback.wait_connected()
self.waitfor(lbcallback.messages, 1, 3)
time.sleep(1)
self.assertEqual(len(lbcallback.messages), 2, lbcallback.messages)
self.assertTrue(lbcallback.messages[0]["message"].properties.MessageExpiryInterval < 6,
lbcallback.messages[0]["message"].properties.MessageExpiryInterval)
self.assertTrue(lbcallback.messages[1]["message"].properties.MessageExpiryInterval < 6,
lbcallback.messages[1]["message"].properties.MessageExpiryInterval)
laclient.disconnect()
lacallback.wait_disconnected()
laclient.loop_stop()
lbclient.disconnect()
lbcallback.wait_disconnected()
lbclient.loop_stop()
def test_subscribe_options(self):
# noLocal
clientid = 'subscribe options - noLocal'
laclient, lacallback = self.new_client(clientid+" a")
laclient.connect(host="localhost", port=self._test_broker_port)
lacallback.wait_connected()
laclient.loop_start()
laclient.subscribe(
topics[0], options=SubscribeOptions(qos=2, noLocal=True))
lacallback.wait_subscribed()
lbclient, lbcallback = self.new_client(clientid+" b")
lbclient.connect(host="localhost", port=self._test_broker_port)
lbcallback.wait_connected()
lbclient.loop_start()
lbclient.subscribe(
topics[0], options=SubscribeOptions(qos=2, noLocal=True))
lbcallback.wait_subscribed()
laclient.publish(topics[0], b"noLocal test", 1, retain=False)
self.waitfor(lbcallback.messages, 1, 3)
time.sleep(1)
self.assertEqual(lacallback.messages, [], lacallback.messages)
self.assertEqual(len(lbcallback.messages), 1, lbcallback.messages)
laclient.disconnect()
lacallback.wait_disconnected()
lbclient.disconnect()
lbcallback.wait_disconnected()
laclient.loop_stop()
lbclient.loop_stop()
# retainAsPublished
clientid = 'subscribe options - retain as published'
laclient, lacallback = self.new_client(clientid+" a")
laclient.connect(host="localhost", port=self._test_broker_port)
lacallback.wait_connected()
laclient.subscribe(topics[0], options=SubscribeOptions(
qos=2, retainAsPublished=True))
lacallback.wait_subscribed()
self.waitfor(lacallback.subscribeds, 1, 3)
laclient.publish(
topics[0], b"retain as published false", 1, retain=False)
laclient.publish(
topics[0], b"retain as published true", 1, retain=True)
self.waitfor(lacallback.messages, 2, 3)
time.sleep(1)
self.assertEqual(len(lacallback.messages), 2, lacallback.messages)
laclient.disconnect()
lacallback.wait_disconnected()
laclient.loop_stop()
self.assertEqual(lacallback.messages[0]["message"].retain, False)
self.assertEqual(lacallback.messages[1]["message"].retain, True)
# retainHandling
clientid = 'subscribe options - retain handling'
laclient, lacallback = self.new_client(clientid+" a")
laclient.connect(host="localhost", port=self._test_broker_port)
lacallback.wait_connected()
laclient.publish(topics[1], b"qos 0", 0, retain=True)
laclient.publish(topics[2], b"qos 1", 1, retain=True)
laclient.publish(topics[3], b"qos 2", 2, retain=True)
time.sleep(1)
# retain handling 1 only gives us retained messages on a new subscription
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=1))
lacallback.wait_subscribed()
self.assertEqual(len(lacallback.messages), 3)
qoss = [lacallback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
lacallback.clear()
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=1))
lacallback.wait_subscribed()
time.sleep(1)
self.assertEqual(len(lacallback.messages), 0)
# remove that subscription
properties = Properties(PacketTypes.UNSUBSCRIBE)
properties.UserProperty = ("a", "2")
properties.UserProperty = ("c", "3")
laclient.unsubscribe(wildtopics[5], properties)
response = lacallback.wait_unsubscribed()
# check that we really did remove that subscription
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=1))
lacallback.wait_subscribed()
self.assertEqual(len(lacallback.messages), 3)
qoss = [lacallback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
lacallback.clear()
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=1))
lacallback.wait_subscribed()
time.sleep(1)
self.assertEqual(len(lacallback.messages), 0)
# remove that subscription
properties = Properties(PacketTypes.UNSUBSCRIBE)
properties.UserProperty = ("a", "2")
properties.UserProperty = ("c", "3")
laclient.unsubscribe(wildtopics[5], properties)
response = lacallback.wait_unsubscribed()
lacallback.clear()
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=2))
lacallback.wait_subscribed()
self.assertEqual(len(lacallback.messages), 0)
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=2))
lacallback.wait_subscribed()
self.assertEqual(len(lacallback.messages), 0)
# remove that subscription
laclient.unsubscribe(wildtopics[5])
response = lacallback.wait_unsubscribed()
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=0))
lacallback.wait_subscribed()
self.assertEqual(len(lacallback.messages), 3)
qoss = [lacallback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
lacallback.clear()
laclient.subscribe(
wildtopics[5], options=SubscribeOptions(2, retainHandling=0))
time.sleep(1)
self.assertEqual(len(lacallback.messages), 3)
qoss = [lacallback.messages[i]["message"].qos for i in range(3)]
self.assertTrue(1 in qoss and 2 in qoss and 0 in qoss, qoss)
laclient.disconnect()
lacallback.wait_disconnected()
laclient.loop_stop()
cleanRetained(self._test_broker_port)
def test_subscription_identifiers(self):
clientid = 'subscription identifiers'
laclient, lacallback = self.new_client(clientid+" a")
laclient.connect(host="localhost", port=self._test_broker_port)
lacallback.wait_connected()
laclient.loop_start()
sub_properties = Properties(PacketTypes.SUBSCRIBE)
sub_properties.SubscriptionIdentifier = 456789
laclient.subscribe(topics[0], qos=2, properties=sub_properties)
lacallback.wait_subscribed()
lbclient, lbcallback = self.new_client(clientid+" b")
lbclient.connect(host="localhost", port=self._test_broker_port)
lbcallback.wait_connected()
lbclient.loop_start()
sub_properties = Properties(PacketTypes.SUBSCRIBE)
sub_properties.SubscriptionIdentifier = 2
lbclient.subscribe(topics[0], qos=2, properties=sub_properties)
lbcallback.wait_subscribed()
sub_properties.clear()
sub_properties.SubscriptionIdentifier = 3
lbclient.subscribe(topics[0]+"/#", qos=2, properties=sub_properties)
lbclient.publish(topics[0], b"sub identifier test", 1, retain=False)
self.waitfor(lacallback.messages, 1, 3)
self.assertEqual(len(lacallback.messages), 1, lacallback.messages)
self.assertEqual(lacallback.messages[0]["message"].properties.SubscriptionIdentifier[0],
456789, lacallback.messages[0]["message"].properties.SubscriptionIdentifier)
laclient.disconnect()
lacallback.wait_disconnected()
laclient.loop_stop()
self.waitfor(lbcallback.messages, 1, 3)
self.assertEqual(len(lbcallback.messages), 1, lbcallback.messages)
expected_subsids = set([2, 3])
received_subsids = set(
lbcallback.messages[0]["message"].properties.SubscriptionIdentifier)
self.assertEqual(received_subsids, expected_subsids, received_subsids)
lbclient.disconnect()
lbcallback.wait_disconnected()
lbclient.loop_stop()
def test_request_response(self):
clientid = 'request response'
laclient, lacallback = self.new_client(clientid+" a")
laclient.connect(host="localhost", port=self._test_broker_port)
lacallback.wait_connected()
laclient.loop_start()
lbclient, lbcallback = self.new_client(clientid+" b")
lbclient.connect(host="localhost", port=self._test_broker_port)
lbcallback.wait_connected()
lbclient.loop_start()
laclient.subscribe(
topics[0], options=SubscribeOptions(2, noLocal=True))
lacallback.wait_subscribed()
lbclient.subscribe(
topics[0], options=SubscribeOptions(2, noLocal=True))
lbcallback.wait_subscribed()
publish_properties = Properties(PacketTypes.PUBLISH)
publish_properties.ResponseTopic = topics[0]
publish_properties.CorrelationData = b"334"
# client a is the requester
laclient.publish(topics[0], b"request", 1,
properties=publish_properties)
# client b is the responder
self.waitfor(lbcallback.messages, 1, 3)
self.assertEqual(len(lbcallback.messages), 1, lbcallback.messages)
self.assertEqual(lbcallback.messages[0]["message"].properties.ResponseTopic, topics[0],
lbcallback.messages[0]["message"].properties)
self.assertEqual(lbcallback.messages[0]["message"].properties.CorrelationData, b"334",
lbcallback.messages[0]["message"].properties)
lbclient.publish(lbcallback.messages[0]["message"].properties.ResponseTopic, b"response", 1,
properties=lbcallback.messages[0]["message"].properties)
# client a gets the response
self.waitfor(lacallback.messages, 1, 3)
self.assertEqual(len(lacallback.messages), 1, lacallback.messages)
laclient.disconnect()
lacallback.wait_disconnected()
laclient.loop_stop()
lbclient.disconnect()
lbcallback.wait_disconnected()
lbclient.loop_stop()
def test_client_topic_alias(self):
clientid = 'client topic alias'
# no server side topic aliases allowed
laclient, lacallback = self.new_client(clientid+" a")
laclient.connect(host="localhost", port=self._test_broker_port)