/
blocking_adapter_test.py
2532 lines (1863 loc) · 91.5 KB
/
blocking_adapter_test.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
"""blocking adapter test"""
from datetime import datetime
import logging
import socket
import time
import unittest
import uuid
from forward_server import ForwardServer
from test_utils import retry_assertion
import pika
from pika.adapters import blocking_connection
from pika.compat import as_bytes
import pika.connection
import pika.exceptions
# Disable warning about access to protected member
# pylint: disable=W0212
# Disable warning Attribute defined outside __init__
# pylint: disable=W0201
# Disable warning Missing docstring
# pylint: disable=C0111
# Disable warning Too many public methods
# pylint: disable=R0904
# Disable warning Invalid variable name
# pylint: disable=C0103
LOGGER = logging.getLogger(__name__)
PARAMS_URL_TEMPLATE = (
'amqp://guest:guest@127.0.0.1:%(port)s/%%2f?socket_timeout=1')
DEFAULT_URL = PARAMS_URL_TEMPLATE % {'port': 5672}
DEFAULT_PARAMS = pika.URLParameters(DEFAULT_URL)
DEFAULT_TIMEOUT = 15
def setUpModule():
logging.basicConfig(level=logging.DEBUG)
class BlockingTestCaseBase(unittest.TestCase):
TIMEOUT = DEFAULT_TIMEOUT
def _connect(self,
url=DEFAULT_URL,
connection_class=pika.BlockingConnection,
impl_class=None):
parameters = pika.URLParameters(url)
connection = connection_class(parameters, _impl_class=impl_class)
self.addCleanup(lambda: connection.close()
if connection.is_open else None)
connection._impl.add_timeout(
self.TIMEOUT, # pylint: disable=E1101
self._on_test_timeout)
return connection
def _on_test_timeout(self):
"""Called when test times out"""
LOGGER.info('%s TIMED OUT (%s)', datetime.utcnow(), self)
self.fail('Test timed out')
@retry_assertion(TIMEOUT/2)
def _assert_exact_message_count_with_retries(self,
channel,
queue,
expected_count):
frame = channel.queue_declare(queue, passive=True)
self.assertEqual(frame.method.message_count, expected_count)
class TestCreateAndCloseConnection(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Create and close connection"""
connection = self._connect()
self.assertIsInstance(connection, pika.BlockingConnection)
self.assertTrue(connection.is_open)
self.assertFalse(connection.is_closed)
self.assertFalse(connection.is_closing)
connection.close()
self.assertTrue(connection.is_closed)
self.assertFalse(connection.is_open)
self.assertFalse(connection.is_closing)
class TestMultiCloseConnection(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Close connection twice"""
connection = self._connect()
self.assertIsInstance(connection, pika.BlockingConnection)
self.assertTrue(connection.is_open)
self.assertFalse(connection.is_closed)
self.assertFalse(connection.is_closing)
connection.close()
self.assertTrue(connection.is_closed)
self.assertFalse(connection.is_open)
self.assertFalse(connection.is_closing)
# Second close call shouldn't crash
connection.close()
class TestConnectionContextManagerClosesConnection(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager closes connection"""
with self._connect() as connection:
self.assertIsInstance(connection, pika.BlockingConnection)
self.assertTrue(connection.is_open)
self.assertTrue(connection.is_closed)
class TestConnectionContextManagerClosesConnectionAndPassesOriginalException(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager closes connection and passes original exception""" # pylint: disable=C0301
class MyException(Exception):
pass
with self.assertRaises(MyException):
with self._connect() as connection:
self.assertTrue(connection.is_open)
raise MyException()
self.assertTrue(connection.is_closed)
class TestConnectionContextManagerClosesConnectionAndPassesSystemException(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager closes connection and passes system exception""" # pylint: disable=C0301
with self.assertRaises(SystemExit):
with self._connect() as connection:
self.assertTrue(connection.is_open)
raise SystemExit()
self.assertTrue(connection.is_closed)
class TestLostConnectionResultsInIsClosedConnectionAndChannel(BlockingTestCaseBase):
def test(self):
connection = self._connect()
channel = connection.channel()
# Simulate the server dropping the socket connection
connection._impl.socket.shutdown(socket.SHUT_RDWR)
with self.assertRaises(pika.exceptions.ConnectionClosed):
# Changing QoS should result in ConnectionClosed
channel.basic_qos()
# Now check is_open/is_closed on channel and connection
self.assertFalse(channel.is_open)
self.assertTrue(channel.is_closed)
self.assertFalse(connection.is_open)
self.assertTrue(connection.is_closed)
class TestInvalidExchangeTypeRaisesConnectionClosed(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: ConnectionClosed raised when creating exchange with invalid type""" # pylint: disable=C0301
# This test exploits behavior specific to RabbitMQ whereby the broker
# closes the connection if an attempt is made to declare an exchange
# with an invalid exchange type
connection = self._connect()
ch = connection.channel()
exg_name = ("TestInvalidExchangeTypeRaisesConnectionClosed_" +
uuid.uuid1().hex)
with self.assertRaises(pika.exceptions.ConnectionClosed) as ex_cm:
# Attempt to create an exchange with invalid exchange type
ch.exchange_declare(exg_name, exchange_type='ZZwwInvalid')
self.assertEqual(ex_cm.exception.args[0], 503)
class TestCreateAndCloseConnectionWithChannelAndConsumer(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Create and close connection with channel and consumer""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
q_name = (
'TestCreateAndCloseConnectionWithChannelAndConsumer_q' +
uuid.uuid1().hex)
body1 = 'a' * 1024
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Publish the message to the queue by way of default exchange
ch.publish(exchange='', routing_key=q_name, body=body1)
# Create a non-ackable consumer
ch.basic_consume(lambda *x: None, q_name, no_ack=True,
exclusive=False, arguments=None)
connection.close()
self.assertTrue(connection.is_closed)
self.assertFalse(connection.is_open)
self.assertFalse(connection.is_closing)
self.assertFalse(connection._impl._channels)
self.assertFalse(ch._consumer_infos)
self.assertFalse(ch._impl._consumers)
class TestSuddenBrokerDisconnectBeforeChannel(BlockingTestCaseBase):
def test(self):
"""BlockingConnection resets properly on TCP/IP drop during channel()
"""
with ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0)) as fwd:
self.connection = self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]})
# Once outside the context, the connection is broken
# BlockingConnection should raise ConnectionClosed
with self.assertRaises(pika.exceptions.ConnectionClosed):
self.connection.channel()
self.assertTrue(self.connection.is_closed)
self.assertFalse(self.connection.is_open)
self.assertIsNone(self.connection._impl.socket)
class TestNoAccessToFileDescriptorAfterConnectionClosed(BlockingTestCaseBase):
def test(self):
"""BlockingConnection no access file descriptor after ConnectionClosed
"""
with ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0)) as fwd:
self.connection = self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]})
# Once outside the context, the connection is broken
# BlockingConnection should raise ConnectionClosed
with self.assertRaises(pika.exceptions.ConnectionClosed):
self.connection.channel()
self.assertTrue(self.connection.is_closed)
self.assertFalse(self.connection.is_open)
self.assertIsNone(self.connection._impl.socket)
# Attempt to operate on the connection once again after ConnectionClosed
self.assertIsNone(self.connection._impl.socket)
with self.assertRaises(pika.exceptions.ConnectionClosed):
self.connection.channel()
class TestConnectWithDownedBroker(BlockingTestCaseBase):
def test(self):
""" BlockingConnection to downed broker results in AMQPConnectionError
"""
# Reserve a port for use in connect
sock = socket.socket()
self.addCleanup(sock.close)
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
sock.close()
with self.assertRaises(pika.exceptions.AMQPConnectionError):
self.connection = self._connect(
PARAMS_URL_TEMPLATE % {"port": port})
class TestDisconnectDuringConnectionStart(BlockingTestCaseBase):
def test(self):
""" BlockingConnection TCP/IP connection loss in CONNECTION_START
"""
fwd = ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0))
fwd.start()
self.addCleanup(lambda: fwd.stop() if fwd.running else None)
class MySelectConnection(pika.SelectConnection):
assert hasattr(pika.SelectConnection, '_on_connection_start')
def _on_connection_start(self, *args, **kwargs):
fwd.stop()
return super(MySelectConnection, self)._on_connection_start(
*args, **kwargs)
with self.assertRaises(pika.exceptions.ProbableAuthenticationError):
self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]},
impl_class=MySelectConnection)
class TestDisconnectDuringConnectionTune(BlockingTestCaseBase):
def test(self):
""" BlockingConnection TCP/IP connection loss in CONNECTION_TUNE
"""
fwd = ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0))
fwd.start()
self.addCleanup(lambda: fwd.stop() if fwd.running else None)
class MySelectConnection(pika.SelectConnection):
assert hasattr(pika.SelectConnection, '_on_connection_tune')
def _on_connection_tune(self, *args, **kwargs):
fwd.stop()
return super(MySelectConnection, self)._on_connection_tune(
*args, **kwargs)
with self.assertRaises(pika.exceptions.ProbableAccessDeniedError):
self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]},
impl_class=MySelectConnection)
class TestDisconnectDuringConnectionProtocol(BlockingTestCaseBase):
def test(self):
""" BlockingConnection TCP/IP connection loss in CONNECTION_PROTOCOL
"""
fwd = ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0))
fwd.start()
self.addCleanup(lambda: fwd.stop() if fwd.running else None)
class MySelectConnection(pika.SelectConnection):
assert hasattr(pika.SelectConnection, '_on_connected')
def _on_connected(self, *args, **kwargs):
fwd.stop()
return super(MySelectConnection, self)._on_connected(
*args, **kwargs)
with self.assertRaises(pika.exceptions.IncompatibleProtocolError):
self._connect(PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]},
impl_class=MySelectConnection)
class TestProcessDataEvents(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.process_data_events"""
connection = self._connect()
# Try with time_limit=0
start_time = time.time()
connection.process_data_events(time_limit=0)
elapsed = time.time() - start_time
self.assertLess(elapsed, 0.25)
# Try with time_limit=0.005
start_time = time.time()
connection.process_data_events(time_limit=0.005)
elapsed = time.time() - start_time
self.assertGreaterEqual(elapsed, 0.005)
self.assertLess(elapsed, 0.25)
class TestConnectionRegisterForBlockAndUnblock(BlockingTestCaseBase):
def test(self):
"""BlockingConnection register for Connection.Blocked/Unblocked"""
connection = self._connect()
# NOTE: I haven't figured out yet how to coerce RabbitMQ to emit
# Connection.Block and Connection.Unblock from the test, so we'll
# just call the registration functions for now, to make sure that
# registration doesn't crash
connection.add_on_connection_blocked_callback(lambda frame: None)
blocked_buffer = []
evt = blocking_connection._ConnectionBlockedEvt(
lambda f: blocked_buffer.append("blocked"),
pika.frame.Method(1, pika.spec.Connection.Blocked('reason')))
repr(evt)
evt.dispatch()
self.assertEqual(blocked_buffer, ["blocked"])
unblocked_buffer = []
connection.add_on_connection_unblocked_callback(lambda frame: None)
evt = blocking_connection._ConnectionUnblockedEvt(
lambda f: unblocked_buffer.append("unblocked"),
pika.frame.Method(1, pika.spec.Connection.Unblocked()))
repr(evt)
evt.dispatch()
self.assertEqual(unblocked_buffer, ["unblocked"])
class TestBlockedConnectionTimeout(BlockingTestCaseBase):
def test(self):
"""BlockingConnection Connection.Blocked timeout """
url = DEFAULT_URL + '&blocked_connection_timeout=0.001'
conn = self._connect(url=url)
# NOTE: I haven't figured out yet how to coerce RabbitMQ to emit
# Connection.Block and Connection.Unblock from the test, so we'll
# simulate it for now
# Simulate Connection.Blocked
conn._impl._on_connection_blocked(pika.frame.Method(
0,
pika.spec.Connection.Blocked('TestBlockedConnectionTimeout')))
# Wait for connection teardown
with self.assertRaises(pika.exceptions.ConnectionClosed) as excCtx:
while True:
conn.process_data_events(time_limit=1)
self.assertEqual(
excCtx.exception.args,
(pika.connection.InternalCloseReasons.BLOCKED_CONNECTION_TIMEOUT,
'Blocked connection timeout expired'))
class TestAddTimeoutRemoveTimeout(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.add_timeout and remove_timeout"""
connection = self._connect()
# Test timer completion
start_time = time.time()
rx_callback = []
timer_id = connection.add_timeout(
0.005,
lambda: rx_callback.append(time.time()))
while not rx_callback:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_callback), 1)
elapsed = time.time() - start_time
self.assertLess(elapsed, 0.25)
# Test removing triggered timeout
connection.remove_timeout(timer_id)
# Test aborted timer
rx_callback = []
timer_id = connection.add_timeout(
0.001,
lambda: rx_callback.append(time.time()))
connection.remove_timeout(timer_id)
connection.process_data_events(time_limit=0.1)
self.assertFalse(rx_callback)
# Make sure _TimerEvt repr doesn't crash
evt = blocking_connection._TimerEvt(lambda: None)
repr(evt)
class TestRemoveTimeoutFromTimeoutCallback(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.remove_timeout from timeout callback"""
connection = self._connect()
# Test timer completion
timer_id1 = connection.add_timeout(5, lambda: 0/0)
rx_timer2 = []
def on_timer2():
connection.remove_timeout(timer_id1)
connection.remove_timeout(timer_id2)
rx_timer2.append(1)
timer_id2 = connection.add_timeout(0, on_timer2)
while not rx_timer2:
connection.process_data_events(time_limit=None)
self.assertNotIn(timer_id1, connection._impl.ioloop._poller._timeouts)
self.assertFalse(connection._ready_events)
class TestSleep(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.sleep"""
connection = self._connect()
# Try with duration=0
start_time = time.time()
connection.sleep(duration=0)
elapsed = time.time() - start_time
self.assertLess(elapsed, 0.25)
# Try with duration=0.005
start_time = time.time()
connection.sleep(duration=0.005)
elapsed = time.time() - start_time
self.assertGreaterEqual(elapsed, 0.005)
self.assertLess(elapsed, 0.25)
class TestConnectionProperties(BlockingTestCaseBase):
def test(self):
"""Test BlockingConnection properties"""
connection = self._connect()
self.assertTrue(connection.is_open)
self.assertFalse(connection.is_closing)
self.assertFalse(connection.is_closed)
self.assertTrue(connection.basic_nack_supported)
self.assertTrue(connection.consumer_cancel_notify_supported)
self.assertTrue(connection.exchange_exchange_bindings_supported)
self.assertTrue(connection.publisher_confirms_supported)
connection.close()
self.assertFalse(connection.is_open)
self.assertFalse(connection.is_closing)
self.assertTrue(connection.is_closed)
class TestCreateAndCloseChannel(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Create and close channel"""
connection = self._connect()
ch = connection.channel()
self.assertIsInstance(ch, blocking_connection.BlockingChannel)
self.assertTrue(ch.is_open)
self.assertFalse(ch.is_closed)
self.assertFalse(ch.is_closing)
self.assertIs(ch.connection, connection)
ch.close()
self.assertTrue(ch.is_closed)
self.assertFalse(ch.is_open)
self.assertFalse(ch.is_closing)
class TestExchangeDeclareAndDelete(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test exchange_declare and exchange_delete"""
connection = self._connect()
ch = connection.channel()
name = "TestExchangeDeclareAndDelete_" + uuid.uuid1().hex
# Declare a new exchange
frame = ch.exchange_declare(name, exchange_type='direct')
self.addCleanup(connection.channel().exchange_delete, name)
self.assertIsInstance(frame.method, pika.spec.Exchange.DeclareOk)
# Check if it exists by declaring it passively
frame = ch.exchange_declare(name, passive=True)
self.assertIsInstance(frame.method, pika.spec.Exchange.DeclareOk)
# Delete the exchange
frame = ch.exchange_delete(name)
self.assertIsInstance(frame.method, pika.spec.Exchange.DeleteOk)
# Verify that it's been deleted
with self.assertRaises(pika.exceptions.ChannelClosed) as cm:
ch.exchange_declare(name, passive=True)
self.assertEqual(cm.exception.args[0], 404)
class TestExchangeBindAndUnbind(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test exchange_bind and exchange_unbind"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestExchangeBindAndUnbind_q' + uuid.uuid1().hex
src_exg_name = 'TestExchangeBindAndUnbind_src_exg_' + uuid.uuid1().hex
dest_exg_name = 'TestExchangeBindAndUnbind_dest_exg_' + uuid.uuid1().hex
routing_key = 'TestExchangeBindAndUnbind'
# Place channel in publisher-acknowledgments mode so that we may test
# whether the queue is reachable by publishing with mandatory=True
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare both exchanges
ch.exchange_declare(src_exg_name, exchange_type='direct')
self.addCleanup(connection.channel().exchange_delete, src_exg_name)
ch.exchange_declare(dest_exg_name, exchange_type='direct')
self.addCleanup(connection.channel().exchange_delete, dest_exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Bind the queue to the destination exchange
ch.queue_bind(q_name, exchange=dest_exg_name, routing_key=routing_key)
# Verify that the queue is unreachable without exchange-exchange binding
with self.assertRaises(pika.exceptions.UnroutableError):
ch.publish(src_exg_name, routing_key, body='', mandatory=True)
# Bind the exchanges
frame = ch.exchange_bind(destination=dest_exg_name, source=src_exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Exchange.BindOk)
# Publish a message via the source exchange
ch.publish(src_exg_name, routing_key, body='TestExchangeBindAndUnbind',
mandatory=True)
# Check that the queue now has one message
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
# Unbind the exchanges
frame = ch.exchange_unbind(destination=dest_exg_name,
source=src_exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Exchange.UnbindOk)
# Verify that the queue is now unreachable via the source exchange
with self.assertRaises(pika.exceptions.UnroutableError):
ch.publish(src_exg_name, routing_key, body='', mandatory=True)
class TestQueueDeclareAndDelete(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test queue_declare and queue_delete"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestQueueDeclareAndDelete_' + uuid.uuid1().hex
# Declare a new queue
frame = ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
self.assertIsInstance(frame.method, pika.spec.Queue.DeclareOk)
# Check if it exists by declaring it passively
frame = ch.queue_declare(q_name, passive=True)
self.assertIsInstance(frame.method, pika.spec.Queue.DeclareOk)
# Delete the queue
frame = ch.queue_delete(q_name)
self.assertIsInstance(frame.method, pika.spec.Queue.DeleteOk)
# Verify that it's been deleted
with self.assertRaises(pika.exceptions.ChannelClosed) as cm:
ch.queue_declare(q_name, passive=True)
self.assertEqual(cm.exception.args[0], 404)
class TestPassiveQueueDeclareOfUnknownQueueRaisesChannelClosed(
BlockingTestCaseBase):
def test(self):
"""BlockingChannel: ChannelClosed raised when passive-declaring unknown queue""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
q_name = ("TestPassiveQueueDeclareOfUnknownQueueRaisesChannelClosed_q_"
+ uuid.uuid1().hex)
with self.assertRaises(pika.exceptions.ChannelClosed) as ex_cm:
ch.queue_declare(q_name, passive=True)
self.assertEqual(ex_cm.exception.args[0], 404)
class TestQueueBindAndUnbindAndPurge(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test queue_bind and queue_unbind"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestQueueBindAndUnbindAndPurge_q' + uuid.uuid1().hex
exg_name = 'TestQueueBindAndUnbindAndPurge_exg_' + uuid.uuid1().hex
routing_key = 'TestQueueBindAndUnbindAndPurge'
# Place channel in publisher-acknowledgments mode so that we may test
# whether the queue is reachable by publishing with mandatory=True
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type='direct')
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Bind the queue to the exchange using routing key
frame = ch.queue_bind(q_name, exchange=exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Queue.BindOk)
# Check that the queue is empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
# Deposit a message in the queue
ch.publish(exg_name, routing_key, body='TestQueueBindAndUnbindAndPurge',
mandatory=True)
# Check that the queue now has one message
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 1)
# Unbind the queue
frame = ch.queue_unbind(queue=q_name, exchange=exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Queue.UnbindOk)
# Verify that the queue is now unreachable via that binding
with self.assertRaises(pika.exceptions.UnroutableError):
ch.publish(exg_name, routing_key,
body='TestQueueBindAndUnbindAndPurge-2',
mandatory=True)
# Purge the queue and verify that 1 message was purged
frame = ch.queue_purge(q_name)
self.assertIsInstance(frame.method, pika.spec.Queue.PurgeOk)
self.assertEqual(frame.method.message_count, 1)
# Verify that the queue is now empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
class TestBasicGet(BlockingTestCaseBase):
def tearDown(self):
LOGGER.info('%s TEARING DOWN (%s)', datetime.utcnow(), self)
def test(self):
"""BlockingChannel.basic_get"""
LOGGER.info('%s STARTED (%s)', datetime.utcnow(), self)
connection = self._connect()
LOGGER.info('%s CONNECTED (%s)', datetime.utcnow(), self)
ch = connection.channel()
LOGGER.info('%s CREATED CHANNEL (%s)', datetime.utcnow(), self)
q_name = 'TestBasicGet_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
LOGGER.info('%s ENABLED PUB-ACKS (%s)', datetime.utcnow(), self)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
LOGGER.info('%s DECLARED QUEUE (%s)', datetime.utcnow(), self)
# Verify result of getting a message from an empty queue
msg = ch.basic_get(q_name, no_ack=False)
self.assertTupleEqual(msg, (None, None, None))
LOGGER.info('%s GOT FROM EMPTY QUEUE (%s)', datetime.utcnow(), self)
body = 'TestBasicGet'
# Deposit a message in the queue via default exchange
ch.publish(exchange='', routing_key=q_name,
body=body,
mandatory=True)
LOGGER.info('%s PUBLISHED (%s)', datetime.utcnow(), self)
# Get the message
(method, properties, body) = ch.basic_get(q_name, no_ack=False)
LOGGER.info('%s GOT FROM NON-EMPTY QUEUE (%s)', datetime.utcnow(), self)
self.assertIsInstance(method, pika.spec.Basic.GetOk)
self.assertEqual(method.delivery_tag, 1)
self.assertFalse(method.redelivered)
self.assertEqual(method.exchange, '')
self.assertEqual(method.routing_key, q_name)
self.assertEqual(method.message_count, 0)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertIsNone(properties.headers)
self.assertEqual(body, as_bytes(body))
# Ack it
ch.basic_ack(delivery_tag=method.delivery_tag)
LOGGER.info('%s ACKED (%s)', datetime.utcnow(), self)
# Verify that the queue is now empty
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestBasicReject(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_reject"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicReject_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Deposit two messages in the queue via default exchange
ch.publish(exchange='', routing_key=q_name,
body='TestBasicReject1',
mandatory=True)
ch.publish(exchange='', routing_key=q_name,
body='TestBasicReject2',
mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicReject1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicReject2'))
# Nack the second message
ch.basic_reject(rx_method.delivery_tag, requeue=True)
# Verify that exactly one message is present in the queue, namely the
# second one
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicReject2'))
class TestBasicRejectNoRequeue(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_reject with requeue=False"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicRejectNoRequeue_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Deposit two messages in the queue via default exchange
ch.publish(exchange='', routing_key=q_name,
body='TestBasicRejectNoRequeue1',
mandatory=True)
ch.publish(exchange='', routing_key=q_name,
body='TestBasicRejectNoRequeue2',
mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicRejectNoRequeue1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicRejectNoRequeue2'))
# Nack the second message
ch.basic_reject(rx_method.delivery_tag, requeue=False)
# Verify that no messages are present in the queue
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestBasicNack(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_nack single message"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicNack_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Deposit two messages in the queue via default exchange
ch.publish(exchange='', routing_key=q_name,
body='TestBasicNack1',
mandatory=True)
ch.publish(exchange='', routing_key=q_name,
body='TestBasicNack2',
mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicNack1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicNack2'))
# Nack the second message
ch.basic_nack(rx_method.delivery_tag, multiple=False, requeue=True)
# Verify that exactly one message is present in the queue, namely the
# second one
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
(rx_method, _, rx_body) = ch.basic_get(q_name, no_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicNack2'))
class TestBasicNackNoRequeue(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_nack with requeue=False"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicNackNoRequeue_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(self._connect().channel().queue_delete, q_name)
# Deposit two messages in the queue via default exchange
ch.publish(exchange='', routing_key=q_name,
body='TestBasicNackNoRequeue1',