-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
test_queues.py
3617 lines (3203 loc) · 176 KB
/
test_queues.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) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import logging
import sys
import os
import json
from concurrent.futures import ThreadPoolExecutor
import types
import pytest
import time
import uuid
from datetime import datetime, timedelta
import calendar
import unittest
import pickle
try:
import uamqp
from azure.servicebus._transport._uamqp_transport import UamqpTransport
except ImportError:
uamqp = None
from azure.servicebus._transport._pyamqp_transport import PyamqpTransport
from azure.servicebus._pyamqp.message import Message
from azure.servicebus._pyamqp import error, client, management_operation
from azure.servicebus import (
ServiceBusClient,
AutoLockRenewer,
TransportType,
ServiceBusMessage,
ServiceBusMessageBatch,
ServiceBusReceivedMessage,
ServiceBusReceiveMode,
ServiceBusSubQueue,
ServiceBusMessageState,
)
from azure.servicebus.amqp import (
AmqpMessageHeader,
AmqpMessageBodyType,
AmqpAnnotatedMessage,
AmqpMessageProperties,
)
from azure.servicebus._common.constants import (
_X_OPT_LOCK_TOKEN,
_X_OPT_PARTITION_KEY,
_X_OPT_VIA_PARTITION_KEY,
_X_OPT_SCHEDULED_ENQUEUE_TIME,
ServiceBusMessageState,
)
from azure.servicebus._common.utils import utc_now
from azure.servicebus.management._models import DictMixin
from azure.servicebus.exceptions import (
ServiceBusConnectionError,
ServiceBusError,
MessageLockLostError,
MessageAlreadySettled,
AutoLockRenewTimeout,
MessageSizeExceededError,
OperationTimeoutError,
)
from devtools_testutils import AzureMgmtRecordedTestCase, get_credential
from servicebus_preparer import (
SERVICEBUS_ENDPOINT_SUFFIX,
CachedServiceBusNamespacePreparer,
ServiceBusQueuePreparer,
CachedServiceBusQueuePreparer,
CachedServiceBusResourceGroupPreparer,
)
from utilities import get_logger, print_message, sleep_until_expired
from mocks import MockReceivedMessage, MockReceiver
from utilities import uamqp_transport as get_uamqp_transport, ArgPasser
uamqp_transport_params, uamqp_transport_ids = get_uamqp_transport()
_logger = get_logger(logging.DEBUG)
# A note regarding live_test_only.
# Old servicebus tests were not written to work on both stubs and live entities.
# This disables those tests for non-live scenarios, and should be removed as tests
# are ported to offline-compatible code.
class TestServiceBusQueue(AzureMgmtRecordedTestCase):
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_receive_and_delete_reconnect_interaction(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
# Note: This test was to guard against github issue 7079
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
sb_client = ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
)
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(5):
sender.send_messages(ServiceBusMessage("ServiceBusMessage {}".format(i)))
with sb_client.get_queue_receiver(
servicebus_queue.name, receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE, max_wait_time=10
) as receiver:
batch = receiver.receive_messages()
count = len(batch)
for message in receiver:
_logger.debug(message)
count += 1
assert count == 5
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer()
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@CachedServiceBusQueuePreparer(
name_prefix="servicebustest", dead_lettering_on_message_expiration=True, lock_duration="PT5S"
)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_github_issue_6178(self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(3):
sender.send_messages(ServiceBusMessage("ServiceBusMessage {}".format(i)))
with sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=60) as receiver:
for message in receiver:
_logger.debug(message)
_logger.debug(message.sequence_number)
_logger.debug(message.enqueued_time_utc)
_logger.debug(message._lock_expired)
receiver.complete_message(message)
time.sleep(10)
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(
name_prefix="servicebustest", dead_lettering_on_message_expiration=True, lock_duration="PT10S"
)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_queue_client_conn_str_receive_handler_peeklock(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
sender = sb_client.get_queue_sender(servicebus_queue.name)
for i in range(10):
message = ServiceBusMessage("Handler message no. {}".format(i))
message.application_properties = {"key": "value"}
message.subject = "label"
message.content_type = "application/text"
message.correlation_id = "cid"
message.message_id = str(i)
message.partition_key = "pk"
message.to = "to"
message.reply_to = "reply_to"
sender.send_messages(message)
# Test that noop empty send works properly.
sender.send_messages([])
sender.send_messages(ServiceBusMessageBatch())
assert len(sender.schedule_messages([], utc_now())) == 0
sender.cancel_scheduled_messages([])
sender.close()
# Then test expected failure modes.
with pytest.raises(ValueError):
with sender:
raise AssertionError("Should raise ValueError")
with pytest.raises(ValueError):
sender.send_messages(ServiceBusMessage("msg"))
with pytest.raises(ValueError):
sender.schedule_messages(ServiceBusMessage("msg"), utc_now())
with pytest.raises(ValueError):
sender.cancel_scheduled_messages([1, 2, 3])
with pytest.raises(ValueError):
sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=0)
receiver = sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=10)
assert len(receiver.receive_deferred_messages([])) == 0
with pytest.raises(ValueError):
receiver.receive_messages(max_wait_time=0)
count = 0
for message in receiver:
print_message(_logger, message)
assert message.delivery_count == 0
assert message.application_properties
assert message.application_properties[b"key"] == b"value"
assert message.subject == "label"
assert message.content_type == "application/text"
assert message.correlation_id == "cid"
assert message.message_id == str(count)
assert message.to == "to"
assert message.reply_to == "reply_to"
assert message.sequence_number
assert message.enqueued_time_utc
assert message.message.delivery_tag is not None
assert message.lock_token == message.message.delivery_annotations.get(_X_OPT_LOCK_TOKEN)
assert message.lock_token == uuid.UUID(bytes_le=message.message.delivery_tag)
assert not message.scheduled_enqueue_time_utc
assert not message.time_to_live
assert not message.session_id
assert not message.reply_to_session_id
count += 1
receiver.complete_message(message)
receiver.close()
with pytest.raises(ValueError):
receiver.receive_messages()
with pytest.raises(ValueError):
with receiver:
raise AssertionError("Should raise ValueError")
with pytest.raises(ValueError):
receiver.receive_deferred_messages([1, 2, 3])
with pytest.raises(ValueError):
receiver.peek_messages()
assert count == 10
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(
name_prefix="servicebustest", dead_lettering_on_message_expiration=True, lock_duration="PT10S"
)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_queue_client_conn_str_receive_handler_release_messages(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
def sub_test_releasing_messages():
# test releasing messages when prefetch is 1 and link credits are issue dynamically
receiver = sb_client.get_queue_receiver(servicebus_queue.name)
sender = sb_client.get_queue_sender(servicebus_queue.name)
with sender, receiver:
# send 10 msgs to queue first
sender.send_messages([ServiceBusMessage("test") for _ in range(5)])
received_msgs = []
# the amount of messages returned by receive call is not stable, especially in live tests
# of different os platforms, this is why a while loop is used here to receive the specific
# amount of message we want to receive
while len(received_msgs) < 5:
# issue link credits more than 5, client should consume 5 msgs from the service in total,
# leaving the extra credits on the wire
for msg in receiver.receive_messages(max_message_count=10, max_wait_time=5):
receiver.complete_message(msg)
received_msgs.append(msg)
assert len(received_msgs) == 5
# send 5 more messages, those messages would arrive at the client while the program is sleeping
sender.send_messages([ServiceBusMessage("test") for _ in range(5)])
time.sleep(15) # sleep > message expiration time
target_msgs_count = 5
received_msgs = []
while len(received_msgs) < target_msgs_count:
# issue 10 link credits, client should consume 5 msgs from the service, leaving no link credits
for msg in receiver.receive_messages(
max_message_count=target_msgs_count - len(received_msgs), max_wait_time=5
):
assert msg.delivery_count == 0 # release would not increase delivery count
receiver.complete_message(msg)
received_msgs.append(msg)
assert len(received_msgs) == 5
def sub_test_releasing_messages_iterator():
# test nested iterator scenario
receiver = sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=10)
sender = sb_client.get_queue_sender(servicebus_queue.name)
with sender, receiver:
# send 5 msgs to queue first
sender.send_messages([ServiceBusMessage("test") for _ in range(5)])
first_time = True
iterator_recv_cnt = 0
# case: iterator + receive batch
for msg in receiver:
assert msg.delivery_count == 0 # release would not increase delivery count
receiver.complete_message(msg)
iterator_recv_cnt += 1
if first_time: # for the first time, we call nested receive message call
received_msgs = []
while len(received_msgs) < 4: # there supposed to be 5 msgs in the queue
# we issue 10 link credits, leaving more credits on the wire
for sub_msg in receiver.receive_messages(max_message_count=10, max_wait_time=5):
assert sub_msg.delivery_count == 0
receiver.complete_message(sub_msg)
received_msgs.append(sub_msg)
assert len(received_msgs) == 4
sender.send_messages([ServiceBusMessage("test") for _ in range(10)])
time.sleep(15) # sleep > message expiration time
received_msgs = []
target_msgs_count = 5 # we want to receive 5 with the receive message call
while len(received_msgs) < target_msgs_count:
for sub_msg in receiver.receive_messages(
max_message_count=target_msgs_count - len(received_msgs), max_wait_time=5
):
assert sub_msg.delivery_count == 0 # release would not increase delivery count
receiver.complete_message(sub_msg)
received_msgs.append(sub_msg)
assert len(received_msgs) == target_msgs_count
first_time = False
assert (
iterator_recv_cnt == 6
) # 1 before nested receive message call + 5 after nested receive message call
# case: iterator + iterator case
sender.send_messages([ServiceBusMessage("test") for _ in range(10)])
outter_recv_cnt = 0
inner_recv_cnt = 0
for msg in receiver:
assert msg.delivery_count == 0
outter_recv_cnt += 1
receiver.complete_message(msg)
for sub_msg in receiver:
assert sub_msg.delivery_count == 0
inner_recv_cnt += 1
receiver.complete_message(sub_msg)
if inner_recv_cnt == 5:
time.sleep(
15
) # innner finish receiving first 5 messages then sleep until lock expiration
break
assert outter_recv_cnt == 1
outter_recv_cnt = 0
for msg in receiver:
assert msg.delivery_count == 0
outter_recv_cnt += 1
receiver.complete_message(msg)
assert outter_recv_cnt == 4
def sub_test_non_releasing_messages():
# test not releasing messages when prefetch is not 1
receiver = sb_client.get_queue_receiver(servicebus_queue.name)
sender = sb_client.get_queue_sender(servicebus_queue.name)
if uamqp_transport:
def _hack_disable_receive_context_message_received(self, message):
# pylint: disable=protected-access
self._handler._was_message_received = True
self._handler._received_messages.put(message)
else:
def _hack_disable_receive_context_message_received(self, frame, message):
# pylint: disable=protected-access
self._handler._last_activity_timestamp = time.time()
self._handler._received_messages.put((frame, message))
with sender, receiver:
# send 5 msgs to queue first
sender.send_messages([ServiceBusMessage("test") for _ in range(5)])
if uamqp_transport:
receiver._handler.message_handler.on_message_received = types.MethodType(
_hack_disable_receive_context_message_received, receiver
)
else:
receiver._handler._link._on_transfer = types.MethodType(
_hack_disable_receive_context_message_received, receiver
)
received_msgs = []
while len(received_msgs) < 5:
# issue 10 link credits, client should consume 5 msgs from the service
# leaving 5 credits on the wire
for msg in receiver.receive_messages(max_message_count=10, max_wait_time=5):
receiver.complete_message(msg)
received_msgs.append(msg)
assert len(received_msgs) == 5
# send 5 more messages, those messages would arrive at the client while the program is sleeping
sender.send_messages([ServiceBusMessage("test") for _ in range(5)])
time.sleep(15) # sleep > message expiration time
# issue 5 link credits, client should consume 5 msgs from the internal buffer which is already lock expired
target_msgs_count = 5
received_msgs = []
while len(received_msgs) < target_msgs_count:
received_msgs.extend(receiver.receive_messages(max_message_count=5, max_wait_time=5))
assert len(received_msgs) == 5
for msg in received_msgs:
# queue ordering I think
assert msg.delivery_count == 0
with pytest.raises(ServiceBusError):
receiver.complete_message(msg)
# re-received message with delivery count increased
target_msgs_count = 5
received_msgs = []
while len(received_msgs) < target_msgs_count:
received_msgs.extend(receiver.receive_messages(max_message_count=5, max_wait_time=5))
assert len(received_msgs) == 5
for msg in received_msgs:
assert msg.delivery_count > 0
receiver.complete_message(msg)
sub_test_releasing_messages()
sub_test_releasing_messages_iterator()
sub_test_non_releasing_messages()
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_queue_client_send_multiple_messages(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
sender = sb_client.get_queue_sender(servicebus_queue.name)
with sender:
messages = []
for i in range(10):
message = ServiceBusMessage("Handler message no. {}".format(i))
message.partition_key = "pkey"
message.time_to_live = timedelta(seconds=60)
message.scheduled_enqueue_time_utc = utc_now() + timedelta(seconds=60)
message.partition_key = None
message.time_to_live = None
message.scheduled_enqueue_time_utc = None
message.session_id = None
messages.append(message)
sender.send_messages(messages)
with pytest.raises(ValueError):
with sender:
raise AssertionError("Should raise ValueError")
with pytest.raises(ValueError):
sender.send_messages(ServiceBusMessage("msg"))
with pytest.raises(ValueError):
sender.schedule_messages(ServiceBusMessage("msg"), utc_now())
with pytest.raises(ValueError):
sender.cancel_scheduled_messages([1, 2, 3])
receiver = sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=5)
with receiver:
count = 0
for message in receiver:
print_message(_logger, message)
assert message.delivery_count == 0
assert not message.application_properties
assert not message.subject
assert not message.content_type
assert not message.correlation_id
assert not message.to
assert not message.reply_to
assert not message.scheduled_enqueue_time_utc
assert not message.time_to_live
assert not message.session_id
assert not message.reply_to_session_id
count += 1
receiver.complete_message(message)
assert count == 10
with pytest.raises(ValueError):
receiver.receive_messages()
with pytest.raises(ValueError):
with receiver:
raise AssertionError("Should raise ValueError")
with pytest.raises(ValueError):
receiver.receive_deferred_messages([1, 2, 3])
with pytest.raises(ValueError):
receiver.peek_messages()
sender = sb_client.get_queue_sender(servicebus_queue.name)
receiver = sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=5)
with sender, receiver:
# send previously unpicklable message
msg = {
"body": "W1tdLCB7ImlucHV0X2lkIjogNH0sIHsiY2FsbGJhY2tzIjogbnVsbCwgImVycmJhY2tzIjogbnVsbCwgImNoYWluIjogbnVsbCwgImNob3JkIjogbnVsbH1d",
"content-encoding": "utf-8",
"content-type": "application/json",
"headers": {
"lang": "py",
"task": "tasks.example_task",
"id": "7c66557d-e4bc-437f-b021-b66dcc39dfdf",
"shadow": None,
"eta": "2021-10-07T02:30:23.764066+00:00",
"expires": None,
"group": None,
"group_index": None,
"retries": 1,
"timelimit": [None, None],
"root_id": "7c66557d-e4bc-437f-b021-b66dcc39dfdf",
"parent_id": "7c66557d-e4bc-437f-b021-b66dcc39dfdf",
"argsrepr": "()",
"kwargsrepr": "{'input_id': 4}",
"origin": "gen36@94713e01a9c0",
"ignore_result": 1,
"x_correlator": "44a1978d-c869-4173-afe4-da741f0edfb9",
},
"properties": {
"correlation_id": "7c66557d-e4bc-437f-b021-b66dcc39dfdf",
"reply_to": "7b9a3672-2fed-3e9b-8bfd-23ae2397d9ad",
"origin": "gen68@c33d4eef123a",
"delivery_mode": 2,
"delivery_info": {"exchange": "", "routing_key": "celery_task_queue"},
"priority": 0,
"body_encoding": "base64",
"delivery_tag": "dc83ddb6-8cdc-4413-b88a-06c56cbde90d",
},
}
sender.send_messages(ServiceBusMessage(json.dumps(msg)))
messages = receiver.receive_messages(max_wait_time=10, max_message_count=1)
# complete first then pickle
receiver.complete_message(messages[0])
if not uamqp_transport:
pickled = pickle.loads(pickle.dumps(messages[0]))
assert json.loads(str(pickled)) == json.loads(str(messages[0]))
else:
with pytest.raises(TypeError):
pickled = pickle.loads(pickle.dumps(messages[0]))
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(
name_prefix="servicebustest", dead_lettering_on_message_expiration=True, lock_duration="PT10S"
)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_queue_client_conn_str_receive_handler_receiveanddelete(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Handler message no. {}".format(i))
sender.send_messages(message)
messages = []
with sb_client.get_queue_receiver(
servicebus_queue.name, receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE, max_wait_time=8
) as receiver:
for message in receiver:
assert not message.application_properties
assert not message.subject
assert not message.content_type
assert not message.correlation_id
assert not message.partition_key
assert not message.to
assert not message.reply_to
assert not message.scheduled_enqueue_time_utc
assert not message.time_to_live
assert not message.session_id
assert not message.reply_to_session_id
messages.append(message)
with pytest.raises(ValueError):
receiver.complete_message(message)
with pytest.raises(ValueError): # RECEIVE_AND_DELETE messages cannot be lock renewed.
renewer = AutoLockRenewer()
renewer.register(receiver, message)
assert len(messages) == 10
assert not receiver._running
time.sleep(10)
messages = []
with sb_client.get_queue_receiver(
servicebus_queue.name, receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE, max_wait_time=5
) as receiver:
for message in receiver:
messages.append(message)
assert len(messages) == 0
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(
name_prefix="servicebustest", dead_lettering_on_message_expiration=True, lock_duration="PT10S"
)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_queue_client_conn_str_receive_handler_receiveanddelete_prefetch(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
# send 10 messages
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Handler message no. {}".format(i))
sender.send_messages(message)
# check peek_messages returns correctly, with default prefetch_count = 0
messages = []
with sb_client.get_queue_receiver(
servicebus_queue.name, receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE, max_wait_time=10
) as receiver:
# peek messages checks current state of queue, which should return 10
# since none were prefetched, added to internal queue, and deleted
peeked_msgs = receiver.peek_messages(max_message_count=10, timeout=10)
assert len(peeked_msgs) == 10
# iterator receives and deletes each message from SB queue
for msg in receiver:
messages.append(msg)
assert len(messages) == 10
# queue should be empty now
peeked_msgs = receiver.peek_messages(max_message_count=10, timeout=10)
assert len(peeked_msgs) == 0
# send 10 messages
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Handler message no. {}".format(i))
sender.send_messages(message)
# check peek_messages returns correctly, with default prefetch_count > 0
messages = []
# prefetch 2 messages from SB queue when receive is called and not on open
with sb_client.get_queue_receiver(
servicebus_queue.name,
receive_mode=ServiceBusReceiveMode.RECEIVE_AND_DELETE,
prefetch_count=2,
max_wait_time=30,
) as receiver:
# peek messages checks current state of SB queue, and returns 10
peeked_msgs = receiver.peek_messages(max_message_count=10, timeout=10)
assert len(peeked_msgs) == 10
# receive 3 messages
recvd_msgs = receiver.receive_messages(max_message_count=3, max_wait_time=10)
assert len(recvd_msgs) == 3
# receive rest of messages in queue
for msg in receiver:
messages.append(msg)
assert len(messages) == 7
# queue should be empty now
peeked_msgs = receiver.peek_messages(max_message_count=10, timeout=10)
assert len(peeked_msgs) == 0
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_queue_client_conn_str_receive_handler_with_stop(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Stop message no. {}".format(i))
sender.send_messages(message)
messages = []
with sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=10) as receiver:
for message in receiver:
messages.append(message)
receiver.complete_message(message)
if len(messages) >= 5:
break
assert receiver._running
assert len(messages) == 5
for message in receiver:
messages.append(message)
receiver.complete_message(message)
if len(messages) >= 5:
break
assert not receiver._running
assert len(messages) == 6
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_servicebus_client_iter_messages_simple(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=10, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Iter message no. {}".format(i))
sender.send_messages(message)
count = 0
for message in receiver:
print_message(_logger, message)
receiver.complete_message(message)
with pytest.raises(MessageAlreadySettled):
receiver.complete_message(message)
with pytest.raises(MessageAlreadySettled):
receiver.renew_message_lock(message)
count += 1
with pytest.raises(StopIteration):
next(receiver)
assert count == 10
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_servicebus_conn_str_client_iter_messages_with_abandon(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Abandoned message no. {}".format(i))
sender.send_messages(message)
count = 0
for message in receiver:
print_message(_logger, message)
if not message.delivery_count:
count += 1
receiver.abandon_message(message)
else:
assert message.delivery_count == 1
receiver.complete_message(message)
assert count == 10
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=20, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
count = 0
for message in receiver:
print_message(_logger, message)
receiver.complete_message(message)
count += 1
assert count == 0
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_servicebus_client_iter_messages_with_defer(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
deferred_messages = []
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Deferred message no. {}".format(i))
sender.send_messages(message)
count = 0
for message in receiver:
deferred_messages.append(message.sequence_number)
print_message(_logger, message)
count += 1
receiver.defer_message(message)
assert count == 10
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
count = 0
for message in receiver:
print_message(_logger, message)
receiver.complete_message(message)
count += 1
assert count == 0
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_servicebus_client_iter_messages_with_retrieve_deferred_client(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
deferred_messages = []
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
for i in range(10):
message = ServiceBusMessage("Deferred message no. {}".format(i))
sender.send_messages(message)
count = 0
for message in receiver:
deferred_messages.append(message.sequence_number)
print_message(_logger, message)
count += 1
receiver.defer_message(message)
assert count == 10
deferred = receiver.receive_deferred_messages(deferred_messages)
assert len(deferred) == 10
for message in deferred:
assert isinstance(message, ServiceBusReceivedMessage)
receiver.complete_message(message)
with pytest.raises(ServiceBusError):
receiver.receive_deferred_messages(deferred_messages)
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_servicebus_client_iter_messages_with_retrieve_deferred_receiver_complete(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
deferred_messages = []
for i in range(10):
message = ServiceBusMessage("Deferred message no. {}".format(i), session_id="test_session")
sender.send_messages(message)
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
count = 0
for message in receiver:
deferred_messages.append(message.sequence_number)
print_message(_logger, message)
count += 1
receiver.defer_message(message)
assert count == 10
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=5, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
deferred = receiver.receive_deferred_messages(deferred_messages)
assert len(deferred) == 10
for message in deferred:
assert isinstance(message, ServiceBusReceivedMessage)
assert message.lock_token
assert message.locked_until_utc
assert message._receiver
receiver.renew_message_lock(message)
receiver.complete_message(message)
@pytest.mark.liveTest
@pytest.mark.live_test_only
@CachedServiceBusResourceGroupPreparer(name_prefix="servicebustest")
@CachedServiceBusNamespacePreparer(name_prefix="servicebustest")
@ServiceBusQueuePreparer(name_prefix="servicebustest", dead_lettering_on_message_expiration=True)
@pytest.mark.parametrize("uamqp_transport", uamqp_transport_params, ids=uamqp_transport_ids)
@ArgPasser()
def test_queue_by_servicebus_client_iter_messages_with_retrieve_deferred_receiver_deadletter(
self, uamqp_transport, *, servicebus_namespace=None, servicebus_queue=None, **kwargs
):
fully_qualified_namespace = f"{servicebus_namespace.name}{SERVICEBUS_ENDPOINT_SUFFIX}"
credential = get_credential()
with ServiceBusClient(
fully_qualified_namespace, credential, logging_enable=False, uamqp_transport=uamqp_transport
) as sb_client:
with sb_client.get_queue_sender(servicebus_queue.name) as sender:
deferred_messages = []
for i in range(10):
message = ServiceBusMessage("Deferred message no. {}".format(i))
sender.send_messages(message)
with sb_client.get_queue_receiver(
servicebus_queue.name, max_wait_time=10, receive_mode=ServiceBusReceiveMode.PEEK_LOCK
) as receiver:
count = 0
for message in receiver:
deferred_messages.append(message.sequence_number)
print_message(_logger, message)
count += 1
receiver.defer_message(message)
assert count == 10
with sb_client.get_queue_receiver(servicebus_queue.name, max_wait_time=10) as receiver:
deferred = receiver.receive_deferred_messages(deferred_messages)
assert len(deferred) == 10
for message in deferred:
assert isinstance(message, ServiceBusReceivedMessage)
receiver.dead_letter_message(
message, reason="Testing reason", error_description="Testing description"
)
count = 0
with sb_client.get_queue_receiver(
servicebus_queue.name, sub_queue=ServiceBusSubQueue.DEAD_LETTER, max_wait_time=10
) as receiver:
for message in receiver:
count += 1
print_message(_logger, message)
assert message.dead_letter_reason == "Testing reason"
assert message.dead_letter_error_description == "Testing description"
assert message.application_properties[b"DeadLetterReason"] == b"Testing reason"