-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Expand file tree
/
Copy pathtest_connection_pool.py
More file actions
1334 lines (1139 loc) · 49.5 KB
/
Copy pathtest_connection_pool.py
File metadata and controls
1334 lines (1139 loc) · 49.5 KB
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
import os
import re
import time
from contextlib import closing
from threading import Thread
from unittest import mock
from unittest.mock import MagicMock
import pytest
import redis
from redis.cache import CacheConfig
from redis.connection import CacheProxyConnection, Connection, to_bool
from redis.event import (
AfterConnectionReleasedEvent,
EventDispatcher,
EventListenerInterface,
)
from redis.maint_notifications import (
MaintNotificationsConfig,
MaintNotificationsPoolHandler,
)
from redis.utils import SSL_AVAILABLE
from .conftest import (
_get_client,
skip_if_redis_enterprise,
skip_if_resp_version,
skip_if_server_version_lt,
)
from .test_pubsub import wait_for_message
if SSL_AVAILABLE:
import ssl
def assert_kwargs_subset(actual, expected):
"""Assert ``expected`` is a subset of ``actual`` (keys present, values equal).
Used by URL/kwargs parsing tests to remain agnostic of auto-injected
connection-pool keys (e.g. maintenance-notifications fields added when
the pool resolves to RESP3) without weakening parsing assertions.
"""
for key, value in expected.items():
assert key in actual, f"missing key {key!r} in {actual!r}"
assert actual[key] == value, (
f"value mismatch for {key!r}: {actual[key]!r} != {value!r}"
)
class DummyConnection:
description_format = "DummyConnection<>"
def __init__(self, **kwargs):
self.kwargs = kwargs
self.pid = os.getpid()
self._sock = None
def connect(self):
self._sock = mock.Mock()
def disconnect(self):
self._sock = None
def can_read(self, timeout: float = 0) -> bool:
return False
def should_reconnect(self):
return False
def re_auth(self):
pass
class TestConnectionPool:
def get_pool(
self,
connection_kwargs=None,
max_connections=None,
connection_class=redis.Connection,
):
connection_kwargs = connection_kwargs or {}
pool = redis.ConnectionPool(
connection_class=connection_class,
max_connections=max_connections,
**connection_kwargs,
)
return pool
@pytest.mark.fixed_client
def test_connection_creation(self):
connection_kwargs = {
"foo": "bar",
"biz": "baz",
}
pool = self.get_pool(
connection_kwargs=connection_kwargs, connection_class=DummyConnection
)
connection = pool.get_connection()
assert isinstance(connection, DummyConnection)
assert_kwargs_subset(connection.kwargs, connection_kwargs)
def test_custom_connection_disables_maint_notifications(self):
pool = redis.ConnectionPool(connection_class=DummyConnection)
assert pool.maint_notifications_enabled() is None
assert "maint_notifications_config" not in pool.connection_kwargs
assert "maint_notifications_pool_handler" not in pool.connection_kwargs
def test_custom_connection_rejects_enabled_maint_notifications_config(self):
with pytest.raises(
redis.RedisError,
match=(
"Maintenance notifications are not supported with .*DummyConnection"
),
):
redis.ConnectionPool(
connection_class=DummyConnection,
maint_notifications_config=MaintNotificationsConfig(enabled=True),
)
@pytest.mark.fixed_client
def test_closing(self):
connection_kwargs = {"foo": "bar", "biz": "baz"}
pool = redis.ConnectionPool(
connection_class=DummyConnection,
max_connections=None,
**connection_kwargs,
)
with closing(pool):
pass
def test_multiple_connections(self, master_host):
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool = self.get_pool(connection_kwargs=connection_kwargs)
c1 = pool.get_connection()
c2 = pool.get_connection()
assert c1 != c2
def test_max_connections(self, master_host):
# Use DummyConnection to avoid actual connection to Redis
# This prevents authentication issues and makes the test more reliable
# while still properly testing the MaxConnectionsError behavior
pool = self.get_pool(max_connections=2, connection_class=DummyConnection)
pool.get_connection()
pool.get_connection()
with pytest.raises(redis.MaxConnectionsError):
pool.get_connection()
def test_reuse_previously_released_connection(self, master_host):
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool = self.get_pool(connection_kwargs=connection_kwargs)
c1 = pool.get_connection()
pool.release(c1)
c2 = pool.get_connection()
assert c1 == c2
def test_release_not_owned_connection(self, master_host):
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool1 = self.get_pool(connection_kwargs=connection_kwargs)
c1 = pool1.get_connection()
pool2 = self.get_pool(
connection_kwargs={"host": master_host[0], "port": master_host[1]}
)
c2 = pool2.get_connection()
pool2.release(c2)
assert len(pool2._available_connections) == 1
pool2.release(c1)
assert len(pool2._available_connections) == 1
@pytest.mark.fixed_client
def test_repr_contains_db_info_tcp(self):
connection_kwargs = {
"host": "localhost",
"port": 6379,
"db": 1,
"client_name": "test-client",
}
pool = self.get_pool(
connection_kwargs=connection_kwargs, connection_class=redis.Connection
)
expected = "host=localhost,port=6379,db=1,client_name=test-client"
assert expected in repr(pool)
@pytest.mark.fixed_client
def test_repr_contains_db_info_unix(self):
connection_kwargs = {"path": "/abc", "db": 1, "client_name": "test-client"}
pool = self.get_pool(
connection_kwargs=connection_kwargs,
connection_class=redis.UnixDomainSocketConnection,
)
expected = "path=/abc,db=1,client_name=test-client"
assert expected in repr(pool)
def test_pool_disconnect(self, master_host):
connection_kwargs = {
"host": master_host[0],
"port": master_host[1],
}
pool = self.get_pool(connection_kwargs=connection_kwargs)
conn = pool.get_connection()
pool.disconnect()
assert not conn._sock
conn.connect()
pool.disconnect(inuse_connections=False)
assert conn._sock
def test_pool_context_manager(self):
pool = self.get_pool(connection_class=DummyConnection)
with pool as entered:
assert entered is pool
conn = pool.get_connection()
conn.connect()
assert conn._sock is not None
# exiting the context closes the pool, disconnecting all connections
assert conn._sock is None
class TestBlockingConnectionPool:
def get_pool(self, connection_kwargs=None, max_connections=10, timeout=20):
connection_kwargs = connection_kwargs or {}
pool = redis.BlockingConnectionPool(
connection_class=DummyConnection,
max_connections=max_connections,
timeout=timeout,
**connection_kwargs,
)
return pool
def test_connection_creation(self, master_host):
connection_kwargs = {
"foo": "bar",
"biz": "baz",
"host": master_host[0],
"port": master_host[1],
}
pool = self.get_pool(connection_kwargs=connection_kwargs)
connection = pool.get_connection()
assert isinstance(connection, DummyConnection)
assert_kwargs_subset(connection.kwargs, connection_kwargs)
def test_multiple_connections(self, master_host):
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool = self.get_pool(connection_kwargs=connection_kwargs)
c1 = pool.get_connection()
c2 = pool.get_connection()
assert c1 != c2
def test_connection_pool_blocks_until_timeout(self, master_host):
"When out of connections, block for timeout seconds, then raise"
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool = self.get_pool(
max_connections=1, timeout=0.1, connection_kwargs=connection_kwargs
)
pool.get_connection()
start = time.monotonic()
with pytest.raises(redis.ConnectionError):
pool.get_connection()
# we should have waited at least 0.1 seconds
assert time.monotonic() - start >= 0.1
def test_connection_pool_blocks_until_conn_available(self, master_host):
"""
When out of connections, block until another connection is released
to the pool
"""
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool = self.get_pool(
max_connections=1, timeout=2, connection_kwargs=connection_kwargs
)
c1 = pool.get_connection()
def target():
time.sleep(0.1)
pool.release(c1)
start = time.monotonic()
Thread(target=target).start()
pool.get_connection()
assert time.monotonic() - start >= 0.1
def test_reuse_previously_released_connection(self, master_host):
connection_kwargs = {"host": master_host[0], "port": master_host[1]}
pool = self.get_pool(connection_kwargs=connection_kwargs)
c1 = pool.get_connection()
pool.release(c1)
c2 = pool.get_connection()
assert c1 == c2
@pytest.mark.fixed_client
def test_repr_contains_db_info_tcp(self):
pool = redis.ConnectionPool(
host="localhost", port=6379, client_name="test-client"
)
expected = "host=localhost,port=6379,client_name=test-client"
assert expected in repr(pool)
@pytest.mark.fixed_client
def test_repr_contains_db_info_unix(self):
pool = redis.ConnectionPool(
connection_class=redis.UnixDomainSocketConnection,
path="abc",
db=0,
client_name="test-client",
)
expected = "path=abc,db=0,client_name=test-client"
assert expected in repr(pool)
@pytest.mark.fixed_client
def test_repr_redacts_sensitive_information(self):
"""Test that __repr__ redacts sensitive values like password and username."""
pool = redis.ConnectionPool(
host="localhost",
port=6379,
password="secret_password_123",
username="myuser",
ssl_password="ssl_secret_456",
db=0,
)
repr_output = repr(pool)
# Verify sensitive values are redacted
assert "secret_password_123" not in repr_output
assert "myuser" not in repr_output
assert "ssl_secret_456" not in repr_output
# Verify the REDACTED placeholder is present
assert "<REDACTED>" in repr_output
# Verify non-sensitive values are still visible
assert "host=localhost" in repr_output
assert "port=6379" in repr_output
assert "db=0" in repr_output
@pytest.mark.onlynoncluster
@skip_if_resp_version(2)
@skip_if_server_version_lt("7.4.0")
def test_initialise_pool_with_cache(self, master_host):
pool = redis.BlockingConnectionPool(
connection_class=Connection,
host=master_host[0],
port=master_host[1],
protocol=3,
cache_config=CacheConfig(),
)
assert isinstance(pool.get_connection(), CacheProxyConnection)
def test_pool_disconnect(self, master_host):
connection_kwargs = {
"foo": "bar",
"biz": "baz",
"host": master_host[0],
"port": master_host[1],
}
pool = self.get_pool(connection_kwargs=connection_kwargs)
conn = pool.get_connection()
pool.disconnect()
assert not conn._sock
conn.connect()
pool.disconnect(inuse_connections=False)
assert conn._sock
def test_pool_context_manager(self):
pool = self.get_pool()
with pool as entered:
assert entered is pool
conn = pool.get_connection()
conn.connect()
assert conn._sock is not None
# exiting the context closes the pool, disconnecting all connections
assert conn._sock is None
@pytest.mark.fixed_client
class TestConnectionPoolURLParsing:
def test_hostname(self):
pool = redis.ConnectionPool.from_url("redis://my.host")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(pool.connection_kwargs, {"host": "my.host"})
def test_quoted_hostname(self):
pool = redis.ConnectionPool.from_url("redis://my %2F host %2B%3D+")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(pool.connection_kwargs, {"host": "my / host +=+"})
def test_port(self):
pool = redis.ConnectionPool.from_url("redis://localhost:6380")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs, {"host": "localhost", "port": 6380}
)
@skip_if_server_version_lt("6.0.0")
def test_username(self):
pool = redis.ConnectionPool.from_url("redis://myuser:@localhost")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs, {"host": "localhost", "username": "myuser"}
)
@skip_if_server_version_lt("6.0.0")
def test_quoted_username(self):
pool = redis.ConnectionPool.from_url(
"redis://%2Fmyuser%2F%2B name%3D%24+:@localhost"
)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs,
{
"host": "localhost",
"username": "/myuser/+ name=$+",
},
)
def test_password(self):
pool = redis.ConnectionPool.from_url("redis://:mypassword@localhost")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs, {"host": "localhost", "password": "mypassword"}
)
def test_quoted_password(self):
pool = redis.ConnectionPool.from_url(
"redis://:%2Fmypass%2F%2B word%3D%24+@localhost"
)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs,
{
"host": "localhost",
"password": "/mypass/+ word=$+",
},
)
@skip_if_server_version_lt("6.0.0")
def test_username_and_password(self):
pool = redis.ConnectionPool.from_url("redis://myuser:mypass@localhost")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs,
{
"host": "localhost",
"username": "myuser",
"password": "mypass",
},
)
def test_db_as_argument(self):
pool = redis.ConnectionPool.from_url("redis://localhost", db=1)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(pool.connection_kwargs, {"host": "localhost", "db": 1})
def test_db_in_path(self):
pool = redis.ConnectionPool.from_url("redis://localhost/2", db=1)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(pool.connection_kwargs, {"host": "localhost", "db": 2})
def test_db_in_querystring(self):
pool = redis.ConnectionPool.from_url("redis://localhost/2?db=3", db=1)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(pool.connection_kwargs, {"host": "localhost", "db": 3})
def test_extra_typed_querystring_options(self):
pool = redis.ConnectionPool.from_url(
"redis://localhost/2?socket_timeout=20&socket_connect_timeout=10"
"&socket_keepalive=&retry_on_timeout=Yes&max_connections=10"
)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs,
{
"host": "localhost",
"db": 2,
"socket_timeout": 20.0,
"socket_connect_timeout": 10.0,
"retry_on_timeout": True,
},
)
assert pool.max_connections == 10
def test_boolean_parsing(self):
for expected, value in (
(None, None),
(None, ""),
(False, 0),
(False, "0"),
(False, "f"),
(False, "F"),
(False, "False"),
(False, "n"),
(False, "N"),
(False, "No"),
(True, 1),
(True, "1"),
(True, "y"),
(True, "Y"),
(True, "Yes"),
):
assert expected is to_bool(value)
def test_client_name_in_querystring(self):
pool = redis.ConnectionPool.from_url("redis://location?client_name=test-client")
assert pool.connection_kwargs["client_name"] == "test-client"
def test_invalid_extra_typed_querystring_options(self):
with pytest.raises(ValueError):
redis.ConnectionPool.from_url(
"redis://localhost/2?socket_timeout=_&socket_connect_timeout=abc"
)
def test_extra_querystring_options(self):
pool = redis.ConnectionPool.from_url("redis://localhost?a=1&b=2")
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs, {"host": "localhost", "a": "1", "b": "2"}
)
def test_calling_from_subclass_returns_correct_instance(self):
pool = redis.BlockingConnectionPool.from_url("redis://localhost")
assert isinstance(pool, redis.BlockingConnectionPool)
def test_client_creates_connection_pool(self):
r = redis.Redis.from_url("redis://myhost")
assert r.connection_pool.connection_class == redis.Connection
assert_kwargs_subset(r.connection_pool.connection_kwargs, {"host": "myhost"})
def test_default_protocol_enables_maint_notifications(self):
"""When ``protocol`` is unspecified the pool resolves to RESP3 and
auto-enables maintenance notifications, injecting handler keys into
``connection_kwargs``."""
pool = redis.ConnectionPool.from_url("redis://localhost")
kwargs = pool.connection_kwargs
assert kwargs.get("host") == "localhost"
# ``protocol=None`` (i.e., absent from the URL) must be preserved on
# the pool kwargs so higher layers can distinguish "empty" from an
# explicit user choice.
assert kwargs.get("protocol") is None
assert isinstance(
kwargs.get("maint_notifications_config"), MaintNotificationsConfig
)
assert isinstance(
kwargs.get("maint_notifications_pool_handler"),
MaintNotificationsPoolHandler,
)
assert "orig_host_address" in kwargs
assert "orig_socket_timeout" in kwargs
assert "orig_socket_connect_timeout" in kwargs
def test_explicit_resp2_does_not_enable_maint_notifications(self):
"""Pinning ``protocol=2`` keeps the legacy behavior — no maintenance
notifications keys are injected."""
pool = redis.ConnectionPool.from_url("redis://localhost?protocol=2")
kwargs = pool.connection_kwargs
assert kwargs.get("host") == "localhost"
assert kwargs.get("protocol") == 2
assert "maint_notifications_config" not in kwargs
assert "maint_notifications_pool_handler" not in kwargs
assert "orig_host_address" not in kwargs
def test_explicit_resp3_enables_maint_notifications(self):
"""Pinning ``protocol=3`` enables maintenance notifications in the
same way as the default (unspecified) case."""
pool = redis.ConnectionPool.from_url("redis://localhost?protocol=3")
kwargs = pool.connection_kwargs
assert kwargs.get("protocol") == 3
assert isinstance(
kwargs.get("maint_notifications_config"), MaintNotificationsConfig
)
def test_invalid_scheme_raises_error(self):
with pytest.raises(ValueError) as cm:
redis.ConnectionPool.from_url("localhost")
assert str(cm.value) == (
"Redis URL must specify one of the following schemes "
"(redis://, rediss://, unix://)"
)
def test_invalid_scheme_raises_error_when_double_slash_missing(self):
with pytest.raises(ValueError) as cm:
redis.ConnectionPool.from_url("redis:foo.bar.com:12345")
assert str(cm.value) == (
"Redis URL must specify one of the following schemes "
"(redis://, rediss://, unix://)"
)
@pytest.mark.fixed_client
class TestBlockingConnectionPoolURLParsing:
def test_extra_typed_querystring_options(self):
pool = redis.BlockingConnectionPool.from_url(
"redis://localhost/2?socket_timeout=20&socket_connect_timeout=10"
"&socket_keepalive=&retry_on_timeout=Yes&max_connections=10&timeout=42"
)
assert pool.connection_class == redis.Connection
assert_kwargs_subset(
pool.connection_kwargs,
{
"host": "localhost",
"db": 2,
"socket_timeout": 20.0,
"socket_connect_timeout": 10.0,
"retry_on_timeout": True,
},
)
assert pool.max_connections == 10
assert pool.timeout == 42.0
def test_invalid_extra_typed_querystring_options(self):
with pytest.raises(ValueError):
redis.BlockingConnectionPool.from_url(
"redis://localhost/2?timeout=_not_a_float_"
)
@pytest.mark.fixed_client
class TestConnectionPoolUnixSocketURLParsing:
def test_defaults(self):
pool = redis.ConnectionPool.from_url("unix:///socket")
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(pool.connection_kwargs, {"path": "/socket"})
def test_client_disables_maint_notifications(self):
client = redis.Redis(unix_socket_path="/socket")
pool = client.connection_pool
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(pool.connection_kwargs, {"path": "/socket"})
assert pool.maint_notifications_enabled() is None
assert "maint_notifications_config" not in pool.connection_kwargs
assert "maint_notifications_pool_handler" not in pool.connection_kwargs
def test_client_respects_disabled_maint_notifications_config(self):
client = redis.Redis(
unix_socket_path="/socket",
maint_notifications_config=MaintNotificationsConfig(enabled=False),
)
pool = client.connection_pool
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(pool.connection_kwargs, {"path": "/socket"})
assert pool.maint_notifications_enabled() is None
assert pool._maint_notifications_pool_handler is None
# The disabled config is consumed by ConnectionPool and should not be
# propagated to individual Unix socket connections.
assert "maint_notifications_config" not in pool.connection_kwargs
assert "maint_notifications_pool_handler" not in pool.connection_kwargs
def test_client_rejects_enabled_maint_notifications_config(self):
with pytest.raises(
redis.RedisError,
match=(
"Maintenance notifications are not supported with Unix "
"domain socket connections"
),
):
redis.Redis(
unix_socket_path="/socket",
maint_notifications_config=MaintNotificationsConfig(enabled=True),
)
def test_pool_rejects_enabled_maint_notifications_config(self):
with pytest.raises(
redis.RedisError,
match=(
"Maintenance notifications are not supported with "
".*UnixDomainSocketConnection"
),
):
redis.ConnectionPool(
connection_class=redis.UnixDomainSocketConnection,
path="/socket",
maint_notifications_config=MaintNotificationsConfig(enabled=True),
)
def test_pool_disables_default_maint_notifications(self):
pool = redis.ConnectionPool(
connection_class=redis.UnixDomainSocketConnection,
path="/socket",
protocol=3,
)
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(pool.connection_kwargs, {"path": "/socket", "protocol": 3})
assert pool.maint_notifications_enabled() is None
assert pool._maint_notifications_pool_handler is None
assert "maint_notifications_config" not in pool.connection_kwargs
assert "maint_notifications_pool_handler" not in pool.connection_kwargs
def test_default_config_client_executes_commands_without_maint_notifications(self):
client = redis.Redis(unix_socket_path="/socket")
key = "redis-py:unix-socket-default-config"
responses = [
{"proto": 3},
b"OK",
b"OK",
b"PONG",
b"OK",
b"value",
]
socket_mock = mock.MagicMock()
with (
mock.patch.object(
redis.UnixDomainSocketConnection, "_connect", return_value=socket_mock
),
mock.patch.object(
redis.UnixDomainSocketConnection, "can_read", return_value=False
),
mock.patch.object(
redis.UnixDomainSocketConnection, "send_command"
) as send_command,
mock.patch.object(
redis.UnixDomainSocketConnection, "read_response", side_effect=responses
),
mock.patch.object(
redis.UnixDomainSocketConnection, "_enable_maintenance_notifications"
) as enable,
):
assert client.ping() is True
assert client.set(key, "value") is True
assert client.get(key) == b"value"
client.close()
enable.assert_not_called()
sent_commands = [command.args for command in send_command.call_args_list]
assert ("PING",) in sent_commands
assert ("SET", key, "value") in sent_commands
assert ("GET", key) in sent_commands
for command in sent_commands:
assert command[:2] != ("CLIENT", "MAINT_NOTIFICATIONS")
def test_connection_does_not_activate_maint_notifications(self):
pool = redis.ConnectionPool(
connection_class=redis.UnixDomainSocketConnection,
path="/socket",
)
conn = pool.make_connection()
with mock.patch.object(conn, "_enable_maintenance_notifications") as enable:
conn.activate_maint_notifications_handling_if_enabled()
enable.assert_not_called()
@skip_if_server_version_lt("6.0.0")
def test_username(self):
pool = redis.ConnectionPool.from_url("unix://myuser:@/socket")
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(
pool.connection_kwargs, {"path": "/socket", "username": "myuser"}
)
@skip_if_server_version_lt("6.0.0")
def test_quoted_username(self):
pool = redis.ConnectionPool.from_url(
"unix://%2Fmyuser%2F%2B name%3D%24+:@/socket"
)
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(
pool.connection_kwargs,
{
"path": "/socket",
"username": "/myuser/+ name=$+",
},
)
def test_password(self):
pool = redis.ConnectionPool.from_url("unix://:mypassword@/socket")
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(
pool.connection_kwargs, {"path": "/socket", "password": "mypassword"}
)
def test_quoted_password(self):
pool = redis.ConnectionPool.from_url(
"unix://:%2Fmypass%2F%2B word%3D%24+@/socket"
)
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(
pool.connection_kwargs,
{
"path": "/socket",
"password": "/mypass/+ word=$+",
},
)
def test_quoted_path(self):
pool = redis.ConnectionPool.from_url(
"unix://:mypassword@/my%2Fpath%2Fto%2F..%2F+_%2B%3D%24ocket"
)
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(
pool.connection_kwargs,
{
"path": "/my/path/to/../+_+=$ocket",
"password": "mypassword",
},
)
def test_db_as_argument(self):
pool = redis.ConnectionPool.from_url("unix:///socket", db=1)
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(pool.connection_kwargs, {"path": "/socket", "db": 1})
def test_db_in_querystring(self):
pool = redis.ConnectionPool.from_url("unix:///socket?db=2", db=1)
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(pool.connection_kwargs, {"path": "/socket", "db": 2})
def test_client_name_in_querystring(self):
pool = redis.ConnectionPool.from_url("redis://location?client_name=test-client")
assert pool.connection_kwargs["client_name"] == "test-client"
def test_extra_querystring_options(self):
pool = redis.ConnectionPool.from_url("unix:///socket?a=1&b=2")
assert pool.connection_class == redis.UnixDomainSocketConnection
assert_kwargs_subset(
pool.connection_kwargs, {"path": "/socket", "a": "1", "b": "2"}
)
def test_connection_class_override(self):
class MyConnection(redis.UnixDomainSocketConnection):
pass
pool = redis.ConnectionPool.from_url(
"unix:///socket", connection_class=MyConnection
)
assert pool.connection_class == MyConnection
@pytest.mark.fixed_client
@pytest.mark.skipif(not SSL_AVAILABLE, reason="SSL not installed")
class TestSSLConnectionURLParsing:
def test_host(self):
pool = redis.ConnectionPool.from_url("rediss://my.host")
assert pool.connection_class == redis.SSLConnection
assert_kwargs_subset(pool.connection_kwargs, {"host": "my.host"})
def test_custom_ssl_context(self):
context = ssl.create_default_context()
class DummyConnectionPool(redis.ConnectionPool):
def get_connection(self):
return self.make_connection()
pool = DummyConnectionPool.from_url("rediss://my.host", ssl_context=context)
assert pool.get_connection().ssl_context is context
def test_connection_class_override(self):
class MyConnection(redis.SSLConnection):
pass
pool = redis.ConnectionPool.from_url(
"rediss://my.host", connection_class=MyConnection
)
assert pool.connection_class == MyConnection
def test_cert_reqs_options(self):
class DummyConnectionPool(redis.ConnectionPool):
def get_connection(self):
return self.make_connection()
pool = DummyConnectionPool.from_url("rediss://?ssl_cert_reqs=none")
assert pool.get_connection().cert_reqs == ssl.CERT_NONE
pool = DummyConnectionPool.from_url("rediss://?ssl_cert_reqs=optional")
assert pool.get_connection().cert_reqs == ssl.CERT_OPTIONAL
pool = DummyConnectionPool.from_url("rediss://?ssl_cert_reqs=required")
assert pool.get_connection().cert_reqs == ssl.CERT_REQUIRED
pool = DummyConnectionPool.from_url("rediss://?ssl_check_hostname=False")
assert pool.get_connection().check_hostname is False
pool = DummyConnectionPool.from_url("rediss://?ssl_check_hostname=True")
assert pool.get_connection().check_hostname is True
def test_ssl_flags_config_parsing(self):
class DummyConnectionPool(redis.ConnectionPool):
def get_connection(self):
return self.make_connection()
pool = DummyConnectionPool.from_url(
"rediss://?ssl_include_verify_flags=VERIFY_X509_STRICT,VERIFY_CRL_CHECK_CHAIN"
)
assert pool.get_connection().ssl_include_verify_flags == [
ssl.VerifyFlags.VERIFY_X509_STRICT,
ssl.VerifyFlags.VERIFY_CRL_CHECK_CHAIN,
]
pool = DummyConnectionPool.from_url(
"rediss://?ssl_include_verify_flags=[VERIFY_X509_STRICT, VERIFY_CRL_CHECK_CHAIN]"
)
assert pool.get_connection().ssl_include_verify_flags == [
ssl.VerifyFlags.VERIFY_X509_STRICT,
ssl.VerifyFlags.VERIFY_CRL_CHECK_CHAIN,
]
pool = DummyConnectionPool.from_url(
"rediss://?ssl_exclude_verify_flags=VERIFY_X509_STRICT, VERIFY_CRL_CHECK_CHAIN"
)
assert pool.get_connection().ssl_exclude_verify_flags == [
ssl.VerifyFlags.VERIFY_X509_STRICT,
ssl.VerifyFlags.VERIFY_CRL_CHECK_CHAIN,
]
pool = DummyConnectionPool.from_url(
"rediss://?ssl_include_verify_flags=VERIFY_X509_STRICT, VERIFY_CRL_CHECK_CHAIN&ssl_exclude_verify_flags=VERIFY_CRL_CHECK_LEAF"
)
assert pool.get_connection().ssl_include_verify_flags == [
ssl.VerifyFlags.VERIFY_X509_STRICT,
ssl.VerifyFlags.VERIFY_CRL_CHECK_CHAIN,
]
assert pool.get_connection().ssl_exclude_verify_flags == [
ssl.VerifyFlags.VERIFY_CRL_CHECK_LEAF,
]
def test_ssl_flags_config_invalid_flag(self):
class DummyConnectionPool(redis.ConnectionPool):
def get_connection(self):
return self.make_connection()
with pytest.raises(ValueError):
DummyConnectionPool.from_url(
"rediss://?ssl_include_verify_flags=[VERIFY_X509,VERIFY_CRL_CHECK_CHAIN]"
)
with pytest.raises(ValueError):
DummyConnectionPool.from_url(
"rediss://?ssl_exclude_verify_flags=[VERIFY_X509_STRICT1, VERIFY_CRL_CHECK_CHAIN]"
)
class TestConnection:
@pytest.mark.fixed_client
def test_on_connect_error(self):
"""
An error in Connection.on_connect should disconnect from the server
see for details: https://github.com/andymccurdy/redis-py/issues/368
"""
# this assumes the Redis server being tested against doesn't have
# 9999 databases ;)
bad_connection = redis.Redis(db=9999)
# an error should be raised on connect
with pytest.raises(redis.RedisError):
bad_connection.info()
pool = bad_connection.connection_pool
assert len(pool._available_connections) == 1
assert not pool._available_connections[0]._sock
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("2.8.8")
@skip_if_redis_enterprise()
def test_busy_loading_disconnects_socket(self, r):
"""
If Redis raises a LOADING error, the connection should be
disconnected and a BusyLoadingError raised
"""
with pytest.raises(redis.BusyLoadingError):
r.execute_command("DEBUG", "ERROR", "LOADING fake message")
assert not r.connection._sock
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("2.8.8")
@skip_if_redis_enterprise()
def test_busy_loading_from_pipeline_immediate_command(self, r):
"""
BusyLoadingErrors should raise from Pipelines that execute a
command immediately, like WATCH does.
"""
pipe = r.pipeline()
with pytest.raises(redis.BusyLoadingError):
pipe.immediate_execute_command("DEBUG", "ERROR", "LOADING fake message")
pool = r.connection_pool
assert pipe.connection
assert pipe.connection in pool._in_use_connections
assert not pipe.connection._sock
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("2.8.8")
@skip_if_redis_enterprise()
def test_busy_loading_from_pipeline(self, r):