-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
test_cluster.py
2853 lines (2488 loc) · 113 KB
/
test_cluster.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
import asyncio
import binascii
import datetime
import os
import warnings
from typing import Any, Awaitable, Callable, Dict, List, Optional, Type, Union
from urllib.parse import urlparse
import pytest
import pytest_asyncio
from _pytest.fixtures import FixtureRequest
from redis.asyncio.cluster import ClusterNode, NodesManager, RedisCluster
from redis.asyncio.connection import Connection, SSLConnection, async_timeout
from redis.asyncio.parser import CommandsParser
from redis.asyncio.retry import Retry
from redis.backoff import ExponentialBackoff, NoBackoff, default_backoff
from redis.cluster import PIPELINE_BLOCKED_COMMANDS, PRIMARY, REPLICA, get_node_name
from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot
from redis.exceptions import (
AskError,
ClusterDownError,
ConnectionError,
DataError,
MaxConnectionsError,
MovedError,
NoPermissionError,
RedisClusterException,
RedisError,
ResponseError,
)
from redis.utils import str_if_bytes
from tests.conftest import (
skip_if_redis_enterprise,
skip_if_server_version_lt,
skip_unless_arch_bits,
)
from .compat import mock
pytestmark = pytest.mark.onlycluster
default_host = "127.0.0.1"
default_port = 7000
default_cluster_slots = [
[0, 8191, ["127.0.0.1", 7000, "node_0"], ["127.0.0.1", 7003, "node_3"]],
[8192, 16383, ["127.0.0.1", 7001, "node_1"], ["127.0.0.1", 7002, "node_2"]],
]
class NodeProxy:
"""A class to proxy a node connection to a different port"""
def __init__(self, addr, redis_addr):
self.addr = addr
self.redis_addr = redis_addr
self.send_event = asyncio.Event()
self.server = None
self.task = None
self.n_connections = 0
async def start(self):
# test that we can connect to redis
async with async_timeout(2):
_, redis_writer = await asyncio.open_connection(*self.redis_addr)
redis_writer.close()
self.server = await asyncio.start_server(
self.handle, *self.addr, reuse_address=True
)
self.task = asyncio.create_task(self.server.serve_forever())
async def handle(self, reader, writer):
# establish connection to redis
redis_reader, redis_writer = await asyncio.open_connection(*self.redis_addr)
try:
self.n_connections += 1
pipe1 = asyncio.create_task(self.pipe(reader, redis_writer))
pipe2 = asyncio.create_task(self.pipe(redis_reader, writer))
await asyncio.gather(pipe1, pipe2)
finally:
redis_writer.close()
async def aclose(self):
self.task.cancel()
try:
await self.task
except asyncio.CancelledError:
pass
await self.server.wait_closed()
async def pipe(
self,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
):
while True:
data = await reader.read(1000)
if not data:
break
writer.write(data)
await writer.drain()
@pytest.fixture
def redis_addr(request):
redis_url = request.config.getoption("--redis-url")
scheme, netloc = urlparse(redis_url)[:2]
assert scheme == "redis"
if ":" in netloc:
host, port = netloc.split(":")
return host, int(port)
else:
return netloc, 6379
@pytest_asyncio.fixture()
async def slowlog(r: RedisCluster) -> None:
"""
Set the slowlog threshold to 0, and the
max length to 128. This will force every
command into the slowlog and allow us
to test it
"""
# Save old values
current_config = await r.config_get(target_nodes=r.get_primaries()[0])
old_slower_than_value = current_config["slowlog-log-slower-than"]
old_max_length_value = current_config["slowlog-max-len"]
# Set the new values
await r.config_set("slowlog-log-slower-than", 0)
await r.config_set("slowlog-max-len", 128)
yield
await r.config_set("slowlog-log-slower-than", old_slower_than_value)
await r.config_set("slowlog-max-len", old_max_length_value)
async def get_mocked_redis_client(*args, **kwargs) -> RedisCluster:
"""
Return a stable RedisCluster object that have deterministic
nodes and slots setup to remove the problem of different IP addresses
on different installations and machines.
"""
cluster_slots = kwargs.pop("cluster_slots", default_cluster_slots)
coverage_res = kwargs.pop("coverage_result", "yes")
cluster_enabled = kwargs.pop("cluster_enabled", True)
with mock.patch.object(ClusterNode, "execute_command") as execute_command_mock:
async def execute_command(*_args, **_kwargs):
if _args[0] == "CLUSTER SLOTS":
mock_cluster_slots = cluster_slots
return mock_cluster_slots
elif _args[0] == "COMMAND":
return {"get": [], "set": []}
elif _args[0] == "INFO":
return {"cluster_enabled": cluster_enabled}
elif len(_args) > 1 and _args[1] == "cluster-require-full-coverage":
return {"cluster-require-full-coverage": coverage_res}
else:
return await execute_command_mock(*_args, **_kwargs)
execute_command_mock.side_effect = execute_command
with mock.patch.object(
CommandsParser, "initialize", autospec=True
) as cmd_parser_initialize:
def cmd_init_mock(self, r: ClusterNode) -> None:
self.commands = {
"GET": {
"name": "get",
"arity": 2,
"flags": ["readonly", "fast"],
"first_key_pos": 1,
"last_key_pos": 1,
"step_count": 1,
}
}
cmd_parser_initialize.side_effect = cmd_init_mock
return await RedisCluster(*args, **kwargs)
def mock_node_resp(node: ClusterNode, response: Any) -> ClusterNode:
connection = mock.AsyncMock()
connection.is_connected = True
connection.read_response.return_value = response
while node._free:
node._free.pop()
node._free.append(connection)
return node
def mock_node_resp_exc(node: ClusterNode, exc: Exception) -> ClusterNode:
connection = mock.AsyncMock()
connection.is_connected = True
connection.read_response.side_effect = exc
while node._free:
node._free.pop()
node._free.append(connection)
return node
def mock_all_nodes_resp(rc: RedisCluster, response: Any) -> RedisCluster:
for node in rc.get_nodes():
mock_node_resp(node, response)
return rc
async def moved_redirection_helper(
create_redis: Callable[..., RedisCluster], failover: bool = False
) -> None:
"""
Test that the client handles MOVED response after a failover.
Redirection after a failover means that the redirection address is of a
replica that was promoted to a primary.
At first call it should return a MOVED ResponseError that will point
the client to the next server it should talk to.
Verify that:
1. it tries to talk to the redirected node
2. it updates the slot's primary to the redirected node
For a failover, also verify:
3. the redirected node's server type updated to 'primary'
4. the server type of the previous slot owner updated to 'replica'
"""
rc = await create_redis(cls=RedisCluster, flushdb=False)
slot = 12182
redirect_node = None
# Get the current primary that holds this slot
prev_primary = rc.nodes_manager.get_node_from_slot(slot)
if failover:
if len(rc.nodes_manager.slots_cache[slot]) < 2:
warnings.warn("Skipping this test since it requires to have a replica")
return
redirect_node = rc.nodes_manager.slots_cache[slot][1]
else:
# Use one of the primaries to be the redirected node
redirect_node = rc.get_primaries()[0]
r_host = redirect_node.host
r_port = redirect_node.port
with mock.patch.object(
ClusterNode, "execute_command", autospec=True
) as execute_command:
def moved_redirect_effect(self, *args, **options):
def ok_response(self, *args, **options):
assert self.host == r_host
assert self.port == r_port
return "MOCK_OK"
execute_command.side_effect = ok_response
raise MovedError(f"{slot} {r_host}:{r_port}")
execute_command.side_effect = moved_redirect_effect
assert await rc.execute_command("SET", "foo", "bar") == "MOCK_OK"
slot_primary = rc.nodes_manager.slots_cache[slot][0]
assert slot_primary == redirect_node
if failover:
assert rc.get_node(host=r_host, port=r_port).server_type == PRIMARY
assert prev_primary.server_type == REPLICA
class TestRedisClusterObj:
"""
Tests for the RedisCluster class
"""
async def test_host_port_startup_node(self) -> None:
"""
Test that it is possible to use host & port arguments as startup node
args
"""
cluster = await get_mocked_redis_client(host=default_host, port=default_port)
assert cluster.get_node(host=default_host, port=default_port) is not None
await cluster.close()
async def test_startup_nodes(self) -> None:
"""
Test that it is possible to use startup_nodes
argument to init the cluster
"""
port_1 = 7000
port_2 = 7001
startup_nodes = [
ClusterNode(default_host, port_1),
ClusterNode(default_host, port_2),
]
cluster = await get_mocked_redis_client(startup_nodes=startup_nodes)
assert (
cluster.get_node(host=default_host, port=port_1) is not None
and cluster.get_node(host=default_host, port=port_2) is not None
)
await cluster.close()
startup_node = ClusterNode("127.0.0.1", 16379)
async with RedisCluster(startup_nodes=[startup_node], client_name="test") as rc:
assert await rc.set("A", 1)
assert await rc.get("A") == b"1"
assert all(
[
name == "test"
for name in (
await rc.client_getname(target_nodes=rc.ALL_NODES)
).values()
]
)
async def test_cluster_set_get_retry_object(self, request: FixtureRequest):
retry = Retry(NoBackoff(), 2)
url = request.config.getoption("--redis-url")
async with RedisCluster.from_url(url, retry=retry) as r:
assert r.get_retry()._retries == retry._retries
assert isinstance(r.get_retry()._backoff, NoBackoff)
for node in r.get_nodes():
n_retry = node.connection_kwargs.get("retry")
assert n_retry is not None
assert n_retry._retries == retry._retries
assert isinstance(n_retry._backoff, NoBackoff)
rand_cluster_node = r.get_random_node()
existing_conn = rand_cluster_node.acquire_connection()
# Change retry policy
new_retry = Retry(ExponentialBackoff(), 3)
r.set_retry(new_retry)
assert r.get_retry()._retries == new_retry._retries
assert isinstance(r.get_retry()._backoff, ExponentialBackoff)
for node in r.get_nodes():
n_retry = node.connection_kwargs.get("retry")
assert n_retry is not None
assert n_retry._retries == new_retry._retries
assert isinstance(n_retry._backoff, ExponentialBackoff)
assert existing_conn.retry._retries == new_retry._retries
new_conn = rand_cluster_node.acquire_connection()
assert new_conn.retry._retries == new_retry._retries
async def test_cluster_retry_object(self, request: FixtureRequest) -> None:
url = request.config.getoption("--redis-url")
async with RedisCluster.from_url(url) as rc_default:
# Test default retry
retry = rc_default.connection_kwargs.get("retry")
assert isinstance(retry, Retry)
assert retry._retries == 3
assert isinstance(retry._backoff, type(default_backoff()))
assert rc_default.get_node("127.0.0.1", 16379).connection_kwargs.get(
"retry"
) == rc_default.get_node("127.0.0.1", 16380).connection_kwargs.get("retry")
retry = Retry(ExponentialBackoff(10, 5), 5)
async with RedisCluster.from_url(url, retry=retry) as rc_custom_retry:
# Test custom retry
assert (
rc_custom_retry.get_node("127.0.0.1", 16379).connection_kwargs.get(
"retry"
)
== retry
)
async with RedisCluster.from_url(
url, connection_error_retry_attempts=0
) as rc_no_retries:
# Test no connection retries
assert (
rc_no_retries.get_node("127.0.0.1", 16379).connection_kwargs.get(
"retry"
)
is None
)
async with RedisCluster.from_url(
url, retry=Retry(NoBackoff(), 0)
) as rc_no_retries:
assert (
rc_no_retries.get_node("127.0.0.1", 16379)
.connection_kwargs.get("retry")
._retries
== 0
)
async def test_empty_startup_nodes(self) -> None:
"""
Test that exception is raised when empty providing empty startup_nodes
"""
with pytest.raises(RedisClusterException) as ex:
RedisCluster(startup_nodes=[])
assert str(ex.value).startswith(
"RedisCluster requires at least one node to discover the cluster"
), str_if_bytes(ex.value)
async def test_from_url(self, request: FixtureRequest) -> None:
url = request.config.getoption("--redis-url")
async with RedisCluster.from_url(url) as rc:
await rc.set("a", 1)
await rc.get("a") == 1
rc = RedisCluster.from_url("rediss://localhost:16379")
assert rc.connection_kwargs["connection_class"] is SSLConnection
async def test_max_connections(
self, create_redis: Callable[..., RedisCluster]
) -> None:
rc = await create_redis(cls=RedisCluster, max_connections=10)
for node in rc.get_nodes():
assert node.max_connections == 10
with mock.patch.object(Connection, "read_response") as read_response:
async def read_response_mocked(*args: Any, **kwargs: Any) -> None:
await asyncio.sleep(10)
read_response.side_effect = read_response_mocked
with pytest.raises(MaxConnectionsError):
await asyncio.gather(
*(
rc.ping(target_nodes=RedisCluster.DEFAULT_NODE)
for _ in range(11)
)
)
await rc.close()
async def test_execute_command_errors(self, r: RedisCluster) -> None:
"""
Test that if no key is provided then exception should be raised.
"""
with pytest.raises(RedisClusterException) as ex:
await r.execute_command("GET")
assert str(ex.value).startswith(
"No way to dispatch this command to Redis Cluster. Missing key."
)
async def test_execute_command_node_flag_primaries(self, r: RedisCluster) -> None:
"""
Test command execution with nodes flag PRIMARIES
"""
primaries = r.get_primaries()
replicas = r.get_replicas()
mock_all_nodes_resp(r, "PONG")
assert await r.ping(target_nodes=RedisCluster.PRIMARIES) is True
for primary in primaries:
conn = primary._free.pop()
assert conn.read_response.called is True
for replica in replicas:
conn = replica._free.pop()
assert conn.read_response.called is not True
async def test_execute_command_node_flag_replicas(self, r: RedisCluster) -> None:
"""
Test command execution with nodes flag REPLICAS
"""
replicas = r.get_replicas()
if not replicas:
r = await get_mocked_redis_client(default_host, default_port)
primaries = r.get_primaries()
mock_all_nodes_resp(r, "PONG")
assert await r.ping(target_nodes=RedisCluster.REPLICAS) is True
for replica in replicas:
conn = replica._free.pop()
assert conn.read_response.called is True
for primary in primaries:
conn = primary._free.pop()
assert conn.read_response.called is not True
await r.close()
async def test_execute_command_node_flag_all_nodes(self, r: RedisCluster) -> None:
"""
Test command execution with nodes flag ALL_NODES
"""
mock_all_nodes_resp(r, "PONG")
assert await r.ping(target_nodes=RedisCluster.ALL_NODES) is True
for node in r.get_nodes():
conn = node._free.pop()
assert conn.read_response.called is True
async def test_execute_command_node_flag_random(self, r: RedisCluster) -> None:
"""
Test command execution with nodes flag RANDOM
"""
mock_all_nodes_resp(r, "PONG")
assert await r.ping(target_nodes=RedisCluster.RANDOM) is True
called_count = 0
for node in r.get_nodes():
conn = node._free.pop()
if conn.read_response.called is True:
called_count += 1
assert called_count == 1
async def test_execute_command_default_node(self, r: RedisCluster) -> None:
"""
Test command execution without node flag is being executed on the
default node
"""
def_node = r.get_default_node()
mock_node_resp(def_node, "PONG")
assert await r.ping() is True
conn = def_node._free.pop()
assert conn.read_response.called
async def test_ask_redirection(self, r: RedisCluster) -> None:
"""
Test that the server handles ASK response.
At first call it should return a ASK ResponseError that will point
the client to the next server it should talk to.
Important thing to verify is that it tries to talk to the second node.
"""
redirect_node = r.get_nodes()[0]
with mock.patch.object(
ClusterNode, "execute_command", autospec=True
) as execute_command:
def ask_redirect_effect(self, *args, **options):
def ok_response(self, *args, **options):
assert self.host == redirect_node.host
assert self.port == redirect_node.port
return "MOCK_OK"
execute_command.side_effect = ok_response
raise AskError(f"12182 {redirect_node.host}:{redirect_node.port}")
execute_command.side_effect = ask_redirect_effect
assert await r.execute_command("SET", "foo", "bar") == "MOCK_OK"
async def test_moved_redirection(
self, create_redis: Callable[..., RedisCluster]
) -> None:
"""
Test that the client handles MOVED response.
"""
await moved_redirection_helper(create_redis, failover=False)
async def test_moved_redirection_after_failover(
self, create_redis: Callable[..., RedisCluster]
) -> None:
"""
Test that the client handles MOVED response after a failover.
"""
await moved_redirection_helper(create_redis, failover=True)
async def test_refresh_using_specific_nodes(
self, create_redis: Callable[..., RedisCluster]
) -> None:
"""
Test making calls on specific nodes when the cluster has failed over to
another node
"""
node_7006 = ClusterNode(host=default_host, port=7006, server_type=PRIMARY)
node_7007 = ClusterNode(host=default_host, port=7007, server_type=PRIMARY)
with mock.patch.object(
ClusterNode, "execute_command", autospec=True
) as execute_command:
with mock.patch.object(
NodesManager, "initialize", autospec=True
) as initialize:
with mock.patch.multiple(
Connection,
send_packed_command=mock.DEFAULT,
connect=mock.DEFAULT,
can_read_destructive=mock.DEFAULT,
) as mocks:
# simulate 7006 as a failed node
def execute_command_mock(self, *args, **options):
if self.port == 7006:
execute_command.failed_calls += 1
raise ClusterDownError(
"CLUSTERDOWN The cluster is "
"down. Use CLUSTER INFO for "
"more information"
)
elif self.port == 7007:
execute_command.successful_calls += 1
def initialize_mock(self):
# start with all slots mapped to 7006
self.nodes_cache = {node_7006.name: node_7006}
self.default_node = node_7006
self.slots_cache = {}
for i in range(0, 16383):
self.slots_cache[i] = [node_7006]
# After the first connection fails, a reinitialize
# should follow the cluster to 7007
def map_7007(self):
self.nodes_cache = {node_7007.name: node_7007}
self.default_node = node_7007
self.slots_cache = {}
for i in range(0, 16383):
self.slots_cache[i] = [node_7007]
# Change initialize side effect for the second call
initialize.side_effect = map_7007
execute_command.side_effect = execute_command_mock
execute_command.successful_calls = 0
execute_command.failed_calls = 0
initialize.side_effect = initialize_mock
mocks["can_read_destructive"].return_value = False
mocks["send_packed_command"].return_value = "MOCK_OK"
mocks["connect"].return_value = None
with mock.patch.object(
CommandsParser, "initialize", autospec=True
) as cmd_parser_initialize:
def cmd_init_mock(self, r: ClusterNode) -> None:
self.commands = {
"GET": {
"name": "get",
"arity": 2,
"flags": ["readonly", "fast"],
"first_key_pos": 1,
"last_key_pos": 1,
"step_count": 1,
}
}
cmd_parser_initialize.side_effect = cmd_init_mock
rc = await create_redis(cls=RedisCluster, flushdb=False)
assert len(rc.get_nodes()) == 1
assert rc.get_node(node_name=node_7006.name) is not None
await rc.get("foo")
# Cluster should now point to 7007, and there should be
# one failed and one successful call
assert len(rc.get_nodes()) == 1
assert rc.get_node(node_name=node_7007.name) is not None
assert rc.get_node(node_name=node_7006.name) is None
assert execute_command.failed_calls == 1
assert execute_command.successful_calls == 1
async def test_reading_from_replicas_in_round_robin(self) -> None:
with mock.patch.multiple(
Connection,
send_command=mock.DEFAULT,
read_response=mock.DEFAULT,
_connect=mock.DEFAULT,
can_read_destructive=mock.DEFAULT,
on_connect=mock.DEFAULT,
) as mocks:
with mock.patch.object(
ClusterNode, "execute_command", autospec=True
) as execute_command:
async def execute_command_mock_first(self, *args, **options):
await self.connection_class(**self.connection_kwargs).connect()
# Primary
assert self.port == 7001
execute_command.side_effect = execute_command_mock_second
return "MOCK_OK"
def execute_command_mock_second(self, *args, **options):
# Replica
assert self.port == 7002
execute_command.side_effect = execute_command_mock_third
return "MOCK_OK"
def execute_command_mock_third(self, *args, **options):
# Primary
assert self.port == 7001
return "MOCK_OK"
# We don't need to create a real cluster connection but we
# do want RedisCluster.on_connect function to get called,
# so we'll mock some of the Connection's functions to allow it
execute_command.side_effect = execute_command_mock_first
mocks["send_command"].return_value = True
mocks["read_response"].return_value = "OK"
mocks["_connect"].return_value = True
mocks["can_read_destructive"].return_value = False
mocks["on_connect"].return_value = True
# Create a cluster with reading from replications
read_cluster = await get_mocked_redis_client(
host=default_host, port=default_port, read_from_replicas=True
)
assert read_cluster.read_from_replicas is True
# Check that we read from the slot's nodes in a round robin
# matter.
# 'foo' belongs to slot 12182 and the slot's nodes are:
# [(127.0.0.1,7001,primary), (127.0.0.1,7002,replica)]
await read_cluster.get("foo")
await read_cluster.get("foo")
await read_cluster.get("foo")
mocks["send_command"].assert_has_calls([mock.call("READONLY")])
await read_cluster.close()
async def test_keyslot(self, r: RedisCluster) -> None:
"""
Test that method will compute correct key in all supported cases
"""
assert r.keyslot("foo") == 12182
assert r.keyslot("{foo}bar") == 12182
assert r.keyslot("{foo}") == 12182
assert r.keyslot(1337) == 4314
assert r.keyslot(125) == r.keyslot(b"125")
assert r.keyslot(125) == r.keyslot("\x31\x32\x35")
assert r.keyslot("大奖") == r.keyslot(b"\xe5\xa4\xa7\xe5\xa5\x96")
assert r.keyslot("大奖") == r.keyslot(b"\xe5\xa4\xa7\xe5\xa5\x96")
assert r.keyslot(1337.1234) == r.keyslot("1337.1234")
assert r.keyslot(1337) == r.keyslot("1337")
assert r.keyslot(b"abc") == r.keyslot("abc")
async def test_get_node_name(self) -> None:
assert (
get_node_name(default_host, default_port)
== f"{default_host}:{default_port}"
)
async def test_all_nodes(self, r: RedisCluster) -> None:
"""
Set a list of nodes and it should be possible to iterate over all
"""
nodes = [node for node in r.nodes_manager.nodes_cache.values()]
for i, node in enumerate(r.get_nodes()):
assert node in nodes
async def test_all_nodes_masters(self, r: RedisCluster) -> None:
"""
Set a list of nodes with random primaries/replicas config and it shold
be possible to iterate over all of them.
"""
nodes = [
node
for node in r.nodes_manager.nodes_cache.values()
if node.server_type == PRIMARY
]
for node in r.get_primaries():
assert node in nodes
@pytest.mark.parametrize("error", RedisCluster.ERRORS_ALLOW_RETRY)
async def test_cluster_down_overreaches_retry_attempts(
self,
error: Union[Type[TimeoutError], Type[ClusterDownError], Type[ConnectionError]],
) -> None:
"""
When error that allows retry is thrown, test that we retry executing
the command as many times as configured in cluster_error_retry_attempts
and then raise the exception
"""
with mock.patch.object(RedisCluster, "_execute_command") as execute_command:
def raise_error(target_node, *args, **kwargs):
execute_command.failed_calls += 1
raise error("mocked error")
execute_command.side_effect = raise_error
rc = await get_mocked_redis_client(host=default_host, port=default_port)
with pytest.raises(error):
await rc.get("bar")
assert execute_command.failed_calls == rc.cluster_error_retry_attempts
await rc.close()
async def test_set_default_node_success(self, r: RedisCluster) -> None:
"""
test successful replacement of the default cluster node
"""
default_node = r.get_default_node()
# get a different node
new_def_node = None
for node in r.get_nodes():
if node != default_node:
new_def_node = node
break
r.set_default_node(new_def_node)
assert r.get_default_node() == new_def_node
async def test_set_default_node_failure(self, r: RedisCluster) -> None:
"""
test failed replacement of the default cluster node
"""
default_node = r.get_default_node()
new_def_node = ClusterNode("1.1.1.1", 1111)
with pytest.raises(DataError):
r.set_default_node(None)
with pytest.raises(DataError):
r.set_default_node(new_def_node)
assert r.get_default_node() == default_node
async def test_get_node_from_key(self, r: RedisCluster) -> None:
"""
Test that get_node_from_key function returns the correct node
"""
key = "bar"
slot = r.keyslot(key)
slot_nodes = r.nodes_manager.slots_cache.get(slot)
primary = slot_nodes[0]
assert r.get_node_from_key(key, replica=False) == primary
replica = r.get_node_from_key(key, replica=True)
if replica is not None:
assert replica.server_type == REPLICA
assert replica in slot_nodes
@skip_if_redis_enterprise()
async def test_not_require_full_coverage_cluster_down_error(
self, r: RedisCluster
) -> None:
"""
When require_full_coverage is set to False (default client config) and not
all slots are covered, if one of the nodes has 'cluster-require_full_coverage'
config set to 'yes' some key-based commands should throw ClusterDownError
"""
node = r.get_node_from_key("foo")
missing_slot = r.keyslot("foo")
assert await r.set("foo", "bar") is True
try:
assert all(await r.cluster_delslots(missing_slot))
with pytest.raises(ClusterDownError):
await r.exists("foo")
finally:
try:
# Add back the missing slot
assert await r.cluster_addslots(node, missing_slot) is True
# Make sure we are not getting ClusterDownError anymore
assert await r.exists("foo") == 1
except ResponseError as e:
if f"Slot {missing_slot} is already busy" in str(e):
# It can happen if the test failed to delete this slot
pass
else:
raise e
async def test_can_run_concurrent_commands(self, request: FixtureRequest) -> None:
url = request.config.getoption("--redis-url")
rc = RedisCluster.from_url(url)
assert all(
await asyncio.gather(
*(rc.echo("i", target_nodes=RedisCluster.ALL_NODES) for i in range(100))
)
)
await rc.close()
def test_replace_cluster_node(self, r: RedisCluster) -> None:
prev_default_node = r.get_default_node()
r.replace_default_node()
assert r.get_default_node() != prev_default_node
r.replace_default_node(prev_default_node)
assert r.get_default_node() == prev_default_node
async def test_default_node_is_replaced_after_exception(self, r):
curr_default_node = r.get_default_node()
# CLUSTER NODES command is being executed on the default node
nodes = await r.cluster_nodes()
assert "myself" in nodes.get(curr_default_node.name).get("flags")
# Mock connection error for the default node
mock_node_resp_exc(curr_default_node, ConnectionError("error"))
# Test that the command succeed from a different node
nodes = await r.cluster_nodes()
assert "myself" not in nodes.get(curr_default_node.name).get("flags")
assert r.get_default_node() != curr_default_node
# Rollback to the old default node
r.replace_default_node(curr_default_node)
async def test_address_remap(self, create_redis, redis_addr):
"""Test that we can create a rediscluster object with
a host-port remapper and map connections through proxy objects
"""
# we remap the first n nodes
offset = 1000
n = 6
ports = [redis_addr[1] + i for i in range(n)]
def address_remap(address):
# remap first three nodes to our local proxy
# old = host, port
host, port = address
if int(port) in ports:
host, port = "127.0.0.1", int(port) + offset
# print(f"{old} {host, port}")
return host, port
# create the proxies
proxies = [
NodeProxy(("127.0.0.1", port + offset), (redis_addr[0], port))
for port in ports
]
await asyncio.gather(*[p.start() for p in proxies])
try:
# create cluster:
r = await create_redis(
cls=RedisCluster, flushdb=False, address_remap=address_remap
)
try:
assert await r.ping() is True
assert await r.set("byte_string", b"giraffe")
assert await r.get("byte_string") == b"giraffe"
finally:
await r.close()
finally:
await asyncio.gather(*[p.aclose() for p in proxies])
# verify that the proxies were indeed used
n_used = sum((1 if p.n_connections else 0) for p in proxies)
assert n_used > 1
class TestClusterRedisCommands:
"""
Tests for RedisCluster unique commands
"""
async def test_get_and_set(self, r: RedisCluster) -> None:
# get and set can't be tested independently of each other
assert await r.get("a") is None
byte_string = b"value"
integer = 5
unicode_string = chr(3456) + "abcd" + chr(3421)
assert await r.set("byte_string", byte_string)
assert await r.set("integer", 5)
assert await r.set("unicode_string", unicode_string)
assert await r.get("byte_string") == byte_string
assert await r.get("integer") == str(integer).encode()
assert (await r.get("unicode_string")).decode("utf-8") == unicode_string
async def test_mget_nonatomic(self, r: RedisCluster) -> None:
assert await r.mget_nonatomic([]) == []
assert await r.mget_nonatomic(["a", "b"]) == [None, None]
await r.set("a", "1")
await r.set("b", "2")
await r.set("c", "3")
assert await r.mget_nonatomic("a", "other", "b", "c") == [
b"1",
None,
b"2",
b"3",
]
async def test_mset_nonatomic(self, r: RedisCluster) -> None:
d = {"a": b"1", "b": b"2", "c": b"3", "d": b"4"}
assert await r.mset_nonatomic(d)
for k, v in d.items():
assert await r.get(k) == v
async def test_config_set(self, r: RedisCluster) -> None:
assert await r.config_set("slowlog-log-slower-than", 0)
async def test_cluster_config_resetstat(self, r: RedisCluster) -> None:
await r.ping(target_nodes="all")
all_info = await r.info(target_nodes="all")
prior_commands_processed = -1
for node_info in all_info.values():
prior_commands_processed = node_info["total_commands_processed"]
assert prior_commands_processed >= 1
await r.config_resetstat(target_nodes="all")
all_info = await r.info(target_nodes="all")
for node_info in all_info.values():
reset_commands_processed = node_info["total_commands_processed"]
assert reset_commands_processed < prior_commands_processed
async def test_client_setname(self, r: RedisCluster) -> None:
node = r.get_random_node()
await r.client_setname("redis_py_test", target_nodes=node)
client_name = await r.client_getname(target_nodes=node)
assert client_name == "redis_py_test"
async def test_exists(self, r: RedisCluster) -> None:
d = {"a": b"1", "b": b"2", "c": b"3", "d": b"4"}
await r.mset_nonatomic(d)
assert await r.exists(*d.keys()) == len(d)
async def test_delete(self, r: RedisCluster) -> None:
d = {"a": b"1", "b": b"2", "c": b"3", "d": b"4"}
await r.mset_nonatomic(d)
assert await r.delete(*d.keys()) == len(d)
assert await r.delete(*d.keys()) == 0
async def test_touch(self, r: RedisCluster) -> None:
d = {"a": b"1", "b": b"2", "c": b"3", "d": b"4"}
await r.mset_nonatomic(d)
assert await r.touch(*d.keys()) == len(d)
async def test_unlink(self, r: RedisCluster) -> None:
d = {"a": b"1", "b": b"2", "c": b"3", "d": b"4"}
await r.mset_nonatomic(d)
assert await r.unlink(*d.keys()) == len(d)