-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathtest_commands.py
3605 lines (3096 loc) · 135 KB
/
test_commands.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
"""
Tests async overrides of commands from their mixins
"""
import asyncio
import binascii
import datetime
import re
import sys
from string import ascii_letters
import pytest
import pytest_asyncio
import redis
from redis import exceptions
from redis._parsers.helpers import (
_RedisCallbacks,
_RedisCallbacksRESP2,
_RedisCallbacksRESP3,
parse_info,
)
from redis.client import EMPTY_RESPONSE, NEVER_DECODE
from redis.commands.json.path import Path
from redis.commands.search.field import TextField
from redis.commands.search.query import Query
from tests.conftest import (
assert_resp_response,
assert_resp_response_in,
is_resp2_connection,
skip_if_server_version_gte,
skip_if_server_version_lt,
skip_unless_arch_bits,
)
if sys.version_info >= (3, 11, 3):
from asyncio import timeout as async_timeout
else:
from async_timeout import timeout as async_timeout
REDIS_6_VERSION = "5.9.0"
@pytest_asyncio.fixture()
async def r_teardown(r: redis.Redis):
"""
A special fixture which removes the provided names from the database after use
"""
usernames = []
def factory(username):
usernames.append(username)
return r
yield factory
try:
client_info = await r.client_info()
except exceptions.NoPermissionError:
client_info = {}
if "default" != client_info.get("user", ""):
await r.auth("", "default")
for username in usernames:
await r.acl_deluser(username)
@pytest_asyncio.fixture()
async def slowlog(r: redis.Redis):
current_config = await r.config_get()
old_slower_than_value = current_config["slowlog-log-slower-than"]
old_max_legnth_value = current_config["slowlog-max-len"]
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_legnth_value)
async def redis_server_time(client: redis.Redis):
seconds, milliseconds = await client.time()
timestamp = float(f"{seconds}.{milliseconds}")
return datetime.datetime.fromtimestamp(timestamp)
async def get_stream_message(client: redis.Redis, stream: str, message_id: str):
"""Fetch a stream message and format it as a (message_id, fields) pair"""
response = await client.xrange(stream, min=message_id, max=message_id)
assert len(response) == 1
return response[0]
# RESPONSE CALLBACKS
@pytest.mark.onlynoncluster
class TestResponseCallbacks:
"""Tests for the response callback system"""
async def test_response_callbacks(self, r: redis.Redis):
callbacks = _RedisCallbacks
if is_resp2_connection(r):
callbacks.update(_RedisCallbacksRESP2)
else:
callbacks.update(_RedisCallbacksRESP3)
assert r.response_callbacks == callbacks
assert id(r.response_callbacks) != id(_RedisCallbacks)
r.set_response_callback("GET", lambda x: "static")
await r.set("a", "foo")
assert await r.get("a") == "static"
async def test_case_insensitive_command_names(self, r: redis.Redis):
assert r.response_callbacks["ping"] == r.response_callbacks["PING"]
class TestRedisCommands:
async def test_command_on_invalid_key_type(self, r: redis.Redis):
await r.lpush("a", "1")
with pytest.raises(redis.ResponseError):
await r.get("a")
# SERVER INFORMATION
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_cat_no_category(self, r: redis.Redis):
categories = await r.acl_cat()
assert isinstance(categories, list)
assert "read" in categories or b"read" in categories
@pytest.mark.redismod
@skip_if_server_version_lt("7.9.0")
async def test_acl_cat_contain_modules_no_category(self, r: redis.Redis):
modules_list = [
"search",
"bloom",
"json",
"cuckoo",
"timeseries",
"cms",
"topk",
"tdigest",
]
categories = await r.acl_cat()
assert isinstance(categories, list)
for module_cat in modules_list:
assert module_cat in categories or module_cat.encode() in categories
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_cat_with_category(self, r: redis.Redis):
commands = await r.acl_cat("read")
assert isinstance(commands, list)
assert "get" in commands or b"get" in commands
@pytest.mark.redismod
@skip_if_server_version_lt("7.9.0")
async def test_acl_modules_cat_with_category(self, r: redis.Redis):
search_commands = await r.acl_cat("search")
assert isinstance(search_commands, list)
assert "FT.SEARCH" in search_commands or b"FT.SEARCH" in search_commands
bloom_commands = await r.acl_cat("bloom")
assert isinstance(bloom_commands, list)
assert "bf.add" in bloom_commands or b"bf.add" in bloom_commands
json_commands = await r.acl_cat("json")
assert isinstance(json_commands, list)
assert "json.get" in json_commands or b"json.get" in json_commands
cuckoo_commands = await r.acl_cat("cuckoo")
assert isinstance(cuckoo_commands, list)
assert "cf.insert" in cuckoo_commands or b"cf.insert" in cuckoo_commands
cms_commands = await r.acl_cat("cms")
assert isinstance(cms_commands, list)
assert "cms.query" in cms_commands or b"cms.query" in cms_commands
topk_commands = await r.acl_cat("topk")
assert isinstance(topk_commands, list)
assert "topk.list" in topk_commands or b"topk.list" in topk_commands
tdigest_commands = await r.acl_cat("tdigest")
assert isinstance(tdigest_commands, list)
assert "tdigest.rank" in tdigest_commands or b"tdigest.rank" in tdigest_commands
timeseries_commands = await r.acl_cat("timeseries")
assert isinstance(timeseries_commands, list)
assert "ts.range" in timeseries_commands or b"ts.range" in timeseries_commands
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_deluser(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
assert await r.acl_deluser(username) == 0
assert await r.acl_setuser(username, enabled=False, reset=True)
assert await r.acl_deluser(username) == 1
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_genpass(self, r: redis.Redis):
password = await r.acl_genpass()
assert isinstance(password, (str, bytes))
@skip_if_server_version_lt("7.0.0")
async def test_acl_getuser_setuser(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
# test enabled=False
assert await r.acl_setuser(username, enabled=False, reset=True)
acl = await r.acl_getuser(username)
assert acl["categories"] == ["-@all"]
assert acl["commands"] == []
assert acl["keys"] == []
assert acl["passwords"] == []
assert "off" in acl["flags"]
assert acl["enabled"] is False
# test nopass=True
assert await r.acl_setuser(username, enabled=True, reset=True, nopass=True)
acl = await r.acl_getuser(username)
assert acl["categories"] == ["-@all"]
assert acl["commands"] == []
assert acl["keys"] == []
assert acl["passwords"] == []
assert "on" in acl["flags"]
assert "nopass" in acl["flags"]
assert acl["enabled"] is True
# test all args
assert await r.acl_setuser(
username,
enabled=True,
reset=True,
passwords=["+pass1", "+pass2"],
categories=["+set", "+@hash", "-geo"],
commands=["+get", "+mget", "-hset"],
keys=["cache:*", "objects:*"],
)
acl = await r.acl_getuser(username)
assert set(acl["categories"]) == {"-@all", "+@set", "+@hash", "-@geo"}
assert set(acl["commands"]) == {"+get", "+mget", "-hset"}
assert acl["enabled"] is True
assert "on" in acl["flags"]
assert set(acl["keys"]) == {"~cache:*", "~objects:*"}
assert len(acl["passwords"]) == 2
# test reset=False keeps existing ACL and applies new ACL on top
assert await r.acl_setuser(
username,
enabled=True,
reset=True,
passwords=["+pass1"],
categories=["+@set"],
commands=["+get"],
keys=["cache:*"],
)
assert await r.acl_setuser(
username,
enabled=True,
passwords=["+pass2"],
categories=["+@hash"],
commands=["+mget"],
keys=["objects:*"],
)
acl = await r.acl_getuser(username)
assert set(acl["commands"]) == {"+get", "+mget"}
assert acl["enabled"] is True
assert "on" in acl["flags"]
assert set(acl["keys"]) == {"~cache:*", "~objects:*"}
assert len(acl["passwords"]) == 2
# test removal of passwords
assert await r.acl_setuser(
username, enabled=True, reset=True, passwords=["+pass1", "+pass2"]
)
assert len((await r.acl_getuser(username))["passwords"]) == 2
assert await r.acl_setuser(username, enabled=True, passwords=["-pass2"])
assert len((await r.acl_getuser(username))["passwords"]) == 1
# Resets and tests that hashed passwords are set properly.
hashed_password = (
"5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"
)
assert await r.acl_setuser(
username, enabled=True, reset=True, hashed_passwords=["+" + hashed_password]
)
acl = await r.acl_getuser(username)
assert acl["passwords"] == [hashed_password]
# test removal of hashed passwords
assert await r.acl_setuser(
username,
enabled=True,
reset=True,
hashed_passwords=["+" + hashed_password],
passwords=["+pass1"],
)
assert len((await r.acl_getuser(username))["passwords"]) == 2
assert await r.acl_setuser(
username, enabled=True, hashed_passwords=["-" + hashed_password]
)
assert len((await r.acl_getuser(username))["passwords"]) == 1
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_list(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
start = await r.acl_list()
assert await r.acl_setuser(username, enabled=False, reset=True)
users = await r.acl_list()
assert len(users) == len(start) + 1
@skip_if_server_version_lt(REDIS_6_VERSION)
@pytest.mark.onlynoncluster
async def test_acl_log(self, r_teardown, create_redis):
username = "redis-py-user"
r = r_teardown(username)
await r.acl_setuser(
username,
enabled=True,
reset=True,
commands=["+get", "+set", "+select"],
keys=["cache:*"],
nopass=True,
)
await r.acl_log_reset()
user_client = await create_redis(username=username)
# Valid operation and key
assert await user_client.set("cache:0", 1)
assert await user_client.get("cache:0") == b"1"
# Invalid key
with pytest.raises(exceptions.NoPermissionError):
await user_client.get("violated_cache:0")
# Invalid operation
with pytest.raises(exceptions.NoPermissionError):
await user_client.hset("cache:0", "hkey", "hval")
assert isinstance(await r.acl_log(), list)
assert len(await r.acl_log()) == 3
assert len(await r.acl_log(count=1)) == 1
assert isinstance((await r.acl_log())[0], dict)
expected = (await r.acl_log(count=1))[0]
assert_resp_response_in(r, "client-info", expected, expected.keys())
assert await r.acl_log_reset()
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_setuser_categories_without_prefix_fails(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
with pytest.raises(exceptions.DataError):
await r.acl_setuser(username, categories=["list"])
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_setuser_commands_without_prefix_fails(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
with pytest.raises(exceptions.DataError):
await r.acl_setuser(username, commands=["get"])
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_setuser_add_passwords_and_nopass_fails(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
with pytest.raises(exceptions.DataError):
await r.acl_setuser(username, passwords="+mypass", nopass=True)
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_users(self, r: redis.Redis):
users = await r.acl_users()
assert isinstance(users, list)
assert len(users) > 0
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_acl_whoami(self, r: redis.Redis):
username = await r.acl_whoami()
assert isinstance(username, (str, bytes))
@pytest.mark.redismod
@skip_if_server_version_lt("7.9.0")
async def test_acl_modules_commands(self, r_teardown):
username = "redis-py-user"
password = "pass-for-test-user"
r = r_teardown(username)
await r.flushdb()
await r.ft().create_index((TextField("txt"),))
await r.hset("doc1", mapping={"txt": "foo baz"})
await r.hset("doc2", mapping={"txt": "foo bar"})
await r.acl_setuser(
username,
enabled=True,
reset=True,
passwords=[f"+{password}"],
categories=["-all"],
commands=[
"+FT.SEARCH",
"-FT.DROPINDEX",
"+json.set",
"+json.get",
"-json.clear",
"+bf.reserve",
"-bf.info",
"+cf.reserve",
"+cms.initbydim",
"+topk.reserve",
"+tdigest.create",
"+ts.create",
"-ts.info",
],
keys=["*"],
)
await r.auth(password, username)
assert await r.ft().search(Query("foo ~bar"))
with pytest.raises(exceptions.NoPermissionError):
await r.ft().dropindex()
await r.json().set("foo", Path.root_path(), "bar")
assert await r.json().get("foo") == "bar"
with pytest.raises(exceptions.NoPermissionError):
await r.json().clear("foo")
assert await r.bf().create("bloom", 0.01, 1000)
assert await r.cf().create("cuckoo", 1000)
assert await r.cms().initbydim("cmsDim", 100, 5)
assert await r.topk().reserve("topk", 5, 100, 5, 0.9)
assert await r.tdigest().create("to-tDigest", 10)
with pytest.raises(exceptions.NoPermissionError):
await r.bf().info("bloom")
assert await r.ts().create(1, labels={"Redis": "Labs"})
with pytest.raises(exceptions.NoPermissionError):
await r.ts().info(1)
@pytest.mark.redismod
@skip_if_server_version_lt("7.9.0")
async def test_acl_modules_category_commands(self, r_teardown):
username = "redis-py-user"
password = "pass-for-test-user"
r = r_teardown(username)
await r.flushdb()
# validate modules categories acl config
await r.acl_setuser(
username,
enabled=True,
reset=True,
passwords=[f"+{password}"],
categories=[
"-all",
"+@search",
"+@json",
"+@bloom",
"+@cuckoo",
"+@topk",
"+@cms",
"+@timeseries",
"+@tdigest",
],
keys=["*"],
)
await r.ft().create_index((TextField("txt"),))
await r.hset("doc1", mapping={"txt": "foo baz"})
await r.hset("doc2", mapping={"txt": "foo bar"})
await r.auth(password, username)
assert await r.ft().search(Query("foo ~bar"))
assert await r.ft().dropindex()
assert await r.json().set("foo", Path.root_path(), "bar")
assert await r.json().get("foo") == "bar"
assert await r.bf().create("bloom", 0.01, 1000)
assert await r.bf().info("bloom")
assert await r.cf().create("cuckoo", 1000)
assert await r.cms().initbydim("cmsDim", 100, 5)
assert await r.topk().reserve("topk", 5, 100, 5, 0.9)
assert await r.tdigest().create("to-tDigest", 10)
assert await r.ts().create(1, labels={"Redis": "Labs"})
assert await r.ts().info(1)
@pytest.mark.onlynoncluster
async def test_client_list(self, r: redis.Redis):
clients = await r.client_list()
assert isinstance(clients[0], dict)
assert "addr" in clients[0]
@skip_if_server_version_lt("5.0.0")
async def test_client_list_type(self, r: redis.Redis):
with pytest.raises(exceptions.RedisError):
await r.client_list(_type="not a client type")
for client_type in ["normal", "master", "replica", "pubsub"]:
clients = await r.client_list(_type=client_type)
assert isinstance(clients, list)
@skip_if_server_version_lt("5.0.0")
@pytest.mark.onlynoncluster
async def test_client_id(self, r: redis.Redis):
assert await r.client_id() > 0
@skip_if_server_version_lt("5.0.0")
@pytest.mark.onlynoncluster
async def test_client_unblock(self, r: redis.Redis):
myid = await r.client_id()
assert not await r.client_unblock(myid)
assert not await r.client_unblock(myid, error=True)
assert not await r.client_unblock(myid, error=False)
@skip_if_server_version_lt("2.6.9")
@pytest.mark.onlynoncluster
async def test_client_getname(self, r: redis.Redis):
assert await r.client_getname() is None
@skip_if_server_version_lt("2.6.9")
@pytest.mark.onlynoncluster
async def test_client_setname(self, r: redis.Redis):
assert await r.client_setname("redis_py_test")
assert_resp_response(
r, await r.client_getname(), "redis_py_test", b"redis_py_test"
)
@skip_if_server_version_lt("7.2.0")
async def test_client_setinfo(self, r: redis.Redis):
await r.ping()
info = await r.client_info()
assert info["lib-name"] == "redis-py"
assert info["lib-ver"] == redis.__version__
assert await r.client_setinfo("lib-name", "test")
assert await r.client_setinfo("lib-ver", "123")
info = await r.client_info()
assert info["lib-name"] == "test"
assert info["lib-ver"] == "123"
r2 = redis.asyncio.Redis(lib_name="test2", lib_version="1234")
info = await r2.client_info()
assert info["lib-name"] == "test2"
assert info["lib-ver"] == "1234"
await r2.aclose()
r3 = redis.asyncio.Redis(lib_name=None, lib_version=None)
info = await r3.client_info()
assert info["lib-name"] == ""
assert info["lib-ver"] == ""
await r3.aclose()
@skip_if_server_version_lt("2.6.9")
@pytest.mark.onlynoncluster
async def test_client_kill(self, r: redis.Redis, r2):
await r.client_setname("redis-py-c1")
await r2.client_setname("redis-py-c2")
clients = [
client
for client in await r.client_list()
if client.get("name") in ["redis-py-c1", "redis-py-c2"]
]
assert len(clients) == 2
clients_by_name = {client.get("name"): client for client in clients}
client_addr = clients_by_name["redis-py-c2"].get("addr")
assert await r.client_kill(client_addr) is True
clients = [
client
for client in await r.client_list()
if client.get("name") in ["redis-py-c1", "redis-py-c2"]
]
assert len(clients) == 1
assert clients[0].get("name") == "redis-py-c1"
@skip_if_server_version_lt("2.8.12")
async def test_client_kill_filter_invalid_params(self, r: redis.Redis):
# empty
with pytest.raises(exceptions.DataError):
await r.client_kill_filter()
# invalid skipme
with pytest.raises(exceptions.DataError):
await r.client_kill_filter(skipme="yeah") # type: ignore
# invalid type
with pytest.raises(exceptions.DataError):
await r.client_kill_filter(_type="caster") # type: ignore
@skip_if_server_version_lt("2.8.12")
@pytest.mark.onlynoncluster
async def test_client_kill_filter_by_id(self, r: redis.Redis, r2):
await r.client_setname("redis-py-c1")
await r2.client_setname("redis-py-c2")
clients = [
client
for client in await r.client_list()
if client.get("name") in ["redis-py-c1", "redis-py-c2"]
]
assert len(clients) == 2
clients_by_name = {client.get("name"): client for client in clients}
client_2_id = clients_by_name["redis-py-c2"].get("id")
resp = await r.client_kill_filter(_id=client_2_id)
assert resp == 1
clients = [
client
for client in await r.client_list()
if client.get("name") in ["redis-py-c1", "redis-py-c2"]
]
assert len(clients) == 1
assert clients[0].get("name") == "redis-py-c1"
@skip_if_server_version_lt("2.8.12")
@pytest.mark.onlynoncluster
async def test_client_kill_filter_by_addr(self, r: redis.Redis, r2):
await r.client_setname("redis-py-c1")
await r2.client_setname("redis-py-c2")
clients = [
client
for client in await r.client_list()
if client.get("name") in ["redis-py-c1", "redis-py-c2"]
]
assert len(clients) == 2
clients_by_name = {client.get("name"): client for client in clients}
client_2_addr = clients_by_name["redis-py-c2"].get("addr")
resp = await r.client_kill_filter(addr=client_2_addr)
assert resp == 1
clients = [
client
for client in await r.client_list()
if client.get("name") in ["redis-py-c1", "redis-py-c2"]
]
assert len(clients) == 1
assert clients[0].get("name") == "redis-py-c1"
@skip_if_server_version_lt("2.6.9")
async def test_client_list_after_client_setname(self, r: redis.Redis):
await r.client_setname("redis_py_test")
clients = await r.client_list()
# we don't know which client ours will be
assert "redis_py_test" in [c["name"] for c in clients]
@skip_if_server_version_lt("2.9.50")
@pytest.mark.onlynoncluster
async def test_client_pause(self, r: redis.Redis):
assert await r.client_pause(1)
assert await r.client_pause(timeout=1)
with pytest.raises(exceptions.RedisError):
await r.client_pause(timeout="not an integer")
@skip_if_server_version_lt("7.2.0")
@pytest.mark.onlynoncluster
async def test_client_no_touch(self, r: redis.Redis):
assert await r.client_no_touch("ON") == b"OK"
assert await r.client_no_touch("OFF") == b"OK"
with pytest.raises(TypeError):
await r.client_no_touch()
async def test_config_get(self, r: redis.Redis):
data = await r.config_get()
assert "maxmemory" in data
assert data["maxmemory"].isdigit()
@pytest.mark.onlynoncluster
async def test_config_resetstat(self, r: redis.Redis):
await r.ping()
prior_commands_processed = int((await r.info())["total_commands_processed"])
assert prior_commands_processed >= 1
await r.config_resetstat()
reset_commands_processed = int((await r.info())["total_commands_processed"])
assert reset_commands_processed < prior_commands_processed
async def test_config_set(self, r: redis.Redis):
await r.config_set("timeout", 70)
assert (await r.config_get())["timeout"] == "70"
assert await r.config_set("timeout", 0)
assert (await r.config_get())["timeout"] == "0"
@pytest.mark.redismod
@skip_if_server_version_lt("7.9.0")
async def test_config_get_for_modules(self, r: redis.Redis):
search_module_configs = await r.config_get("search-*")
assert "search-timeout" in search_module_configs
ts_module_configs = await r.config_get("ts-*")
assert "ts-retention-policy" in ts_module_configs
bf_module_configs = await r.config_get("bf-*")
assert "bf-error-rate" in bf_module_configs
cf_module_configs = await r.config_get("cf-*")
assert "cf-initial-size" in cf_module_configs
@pytest.mark.redismod
@skip_if_server_version_lt("7.9.0")
async def test_config_set_for_search_module(self, r: redis.Redis):
config = await r.config_get("*")
initial_default_search_dialect = config["search-default-dialect"]
try:
default_dialect_new = "3"
assert await r.config_set("search-default-dialect", default_dialect_new)
assert (await r.config_get("*"))[
"search-default-dialect"
] == default_dialect_new
assert (
(await r.ft().config_get("*"))[b"DEFAULT_DIALECT"]
).decode() == default_dialect_new
except AssertionError as ex:
raise ex
finally:
assert await r.config_set(
"search-default-dialect", initial_default_search_dialect
)
with pytest.raises(exceptions.ResponseError):
await r.config_set("search-max-doctablesize", 2000000)
@pytest.mark.onlynoncluster
async def test_dbsize(self, r: redis.Redis):
await r.set("a", "foo")
await r.set("b", "bar")
assert await r.dbsize() == 2
@pytest.mark.onlynoncluster
async def test_echo(self, r: redis.Redis):
assert await r.echo("foo bar") == b"foo bar"
@pytest.mark.onlynoncluster
async def test_info(self, r: redis.Redis):
await r.set("a", "foo")
await r.set("b", "bar")
info = await r.info()
assert isinstance(info, dict)
assert "arch_bits" in info.keys()
assert "redis_version" in info.keys()
@pytest.mark.onlynoncluster
async def test_lastsave(self, r: redis.Redis):
assert isinstance(await r.lastsave(), datetime.datetime)
async def test_object(self, r: redis.Redis):
await r.set("a", "foo")
assert isinstance(await r.object("refcount", "a"), int)
assert isinstance(await r.object("idletime", "a"), int)
assert await r.object("encoding", "a") in (b"raw", b"embstr")
assert await r.object("idletime", "invalid-key") is None
async def test_ping(self, r: redis.Redis):
assert await r.ping()
@pytest.mark.onlynoncluster
async def test_slowlog_get(self, r: redis.Redis, slowlog):
assert await r.slowlog_reset()
unicode_string = chr(3456) + "abcd" + chr(3421)
await r.get(unicode_string)
slowlog = await r.slowlog_get()
assert isinstance(slowlog, list)
commands = [log["command"] for log in slowlog]
get_command = b" ".join((b"GET", unicode_string.encode("utf-8")))
assert get_command in commands
assert b"SLOWLOG RESET" in commands
# the order should be ['GET <uni string>', 'SLOWLOG RESET'],
# but if other clients are executing commands at the same time, there
# could be commands, before, between, or after, so just check that
# the two we care about are in the appropriate order.
assert commands.index(get_command) < commands.index(b"SLOWLOG RESET")
# make sure other attributes are typed correctly
assert isinstance(slowlog[0]["start_time"], int)
assert isinstance(slowlog[0]["duration"], int)
@pytest.mark.onlynoncluster
async def test_slowlog_get_limit(self, r: redis.Redis, slowlog):
assert await r.slowlog_reset()
await r.get("foo")
slowlog = await r.slowlog_get(1)
assert isinstance(slowlog, list)
# only one command, based on the number we passed to slowlog_get()
assert len(slowlog) == 1
@pytest.mark.onlynoncluster
async def test_slowlog_length(self, r: redis.Redis, slowlog):
await r.get("foo")
assert isinstance(await r.slowlog_len(), int)
@skip_if_server_version_lt("2.6.0")
async def test_time(self, r: redis.Redis):
t = await r.time()
assert len(t) == 2
assert isinstance(t[0], int)
assert isinstance(t[1], int)
async def test_never_decode_option(self, r: redis.Redis):
opts = {NEVER_DECODE: []}
await r.delete("a")
assert await r.execute_command("EXISTS", "a", **opts) == 0
async def test_empty_response_option(self, r: redis.Redis):
opts = {EMPTY_RESPONSE: []}
await r.delete("a")
assert await r.execute_command("EXISTS", "a", **opts) == 0
# BASIC KEY COMMANDS
async def test_append(self, r: redis.Redis):
assert await r.append("a", "a1") == 2
assert await r.get("a") == b"a1"
assert await r.append("a", "a2") == 4
assert await r.get("a") == b"a1a2"
@skip_if_server_version_lt("2.6.0")
async def test_bitcount(self, r: redis.Redis):
await r.setbit("a", 5, True)
assert await r.bitcount("a") == 1
await r.setbit("a", 6, True)
assert await r.bitcount("a") == 2
await r.setbit("a", 5, False)
assert await r.bitcount("a") == 1
await r.setbit("a", 9, True)
await r.setbit("a", 17, True)
await r.setbit("a", 25, True)
await r.setbit("a", 33, True)
assert await r.bitcount("a") == 5
assert await r.bitcount("a", 0, -1) == 5
assert await r.bitcount("a", 2, 3) == 2
assert await r.bitcount("a", 2, -1) == 3
assert await r.bitcount("a", -2, -1) == 2
assert await r.bitcount("a", 1, 1) == 1
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_not_empty_string(self, r: redis.Redis):
await r.set("a", "")
await r.bitop("not", "r", "a")
assert await r.get("r") is None
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_not(self, r: redis.Redis):
test_str = b"\xAA\x00\xFF\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
await r.set("a", test_str)
await r.bitop("not", "r", "a")
assert int(binascii.hexlify(await r.get("r")), 16) == correct
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_not_in_place(self, r: redis.Redis):
test_str = b"\xAA\x00\xFF\x55"
correct = ~0xAA00FF55 & 0xFFFFFFFF
await r.set("a", test_str)
await r.bitop("not", "a", "a")
assert int(binascii.hexlify(await r.get("a")), 16) == correct
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_single_string(self, r: redis.Redis):
test_str = b"\x01\x02\xFF"
await r.set("a", test_str)
await r.bitop("and", "res1", "a")
await r.bitop("or", "res2", "a")
await r.bitop("xor", "res3", "a")
assert await r.get("res1") == test_str
assert await r.get("res2") == test_str
assert await r.get("res3") == test_str
@skip_if_server_version_lt("2.6.0")
@pytest.mark.onlynoncluster
async def test_bitop_string_operands(self, r: redis.Redis):
await r.set("a", b"\x01\x02\xFF\xFF")
await r.set("b", b"\x01\x02\xFF")
await r.bitop("and", "res1", "a", "b")
await r.bitop("or", "res2", "a", "b")
await r.bitop("xor", "res3", "a", "b")
assert int(binascii.hexlify(await r.get("res1")), 16) == 0x0102FF00
assert int(binascii.hexlify(await r.get("res2")), 16) == 0x0102FFFF
assert int(binascii.hexlify(await r.get("res3")), 16) == 0x000000FF
@pytest.mark.onlynoncluster
@skip_if_server_version_lt("2.8.7")
async def test_bitpos(self, r: redis.Redis):
key = "key:bitpos"
await r.set(key, b"\xff\xf0\x00")
assert await r.bitpos(key, 0) == 12
assert await r.bitpos(key, 0, 2, -1) == 16
assert await r.bitpos(key, 0, -2, -1) == 12
await r.set(key, b"\x00\xff\xf0")
assert await r.bitpos(key, 1, 0) == 8
assert await r.bitpos(key, 1, 1) == 8
await r.set(key, b"\x00\x00\x00")
assert await r.bitpos(key, 1) == -1
@skip_if_server_version_lt("2.8.7")
async def test_bitpos_wrong_arguments(self, r: redis.Redis):
key = "key:bitpos:wrong:args"
await r.set(key, b"\xff\xf0\x00")
with pytest.raises(exceptions.RedisError):
await r.bitpos(key, 0, end=1) == 12
with pytest.raises(exceptions.RedisError):
await r.bitpos(key, 7) == 12
async def test_decr(self, r: redis.Redis):
assert await r.decr("a") == -1
assert await r.get("a") == b"-1"
assert await r.decr("a") == -2
assert await r.get("a") == b"-2"
assert await r.decr("a", amount=5) == -7
assert await r.get("a") == b"-7"
async def test_decrby(self, r: redis.Redis):
assert await r.decrby("a", amount=2) == -2
assert await r.decrby("a", amount=3) == -5
assert await r.get("a") == b"-5"
async def test_delete(self, r: redis.Redis):
assert await r.delete("a") == 0
await r.set("a", "foo")
assert await r.delete("a") == 1
async def test_delete_with_multiple_keys(self, r: redis.Redis):
await r.set("a", "foo")
await r.set("b", "bar")
assert await r.delete("a", "b") == 2
assert await r.get("a") is None
assert await r.get("b") is None
async def test_delitem(self, r: redis.Redis):
await r.set("a", "foo")
await r.delete("a")
assert await r.get("a") is None
@skip_if_server_version_lt("4.0.0")
async def test_unlink(self, r: redis.Redis):
assert await r.unlink("a") == 0
await r.set("a", "foo")
assert await r.unlink("a") == 1
assert await r.get("a") is None
@skip_if_server_version_lt("4.0.0")
async def test_unlink_with_multiple_keys(self, r: redis.Redis):
await r.set("a", "foo")
await r.set("b", "bar")
assert await r.unlink("a", "b") == 2
assert await r.get("a") is None
assert await r.get("b") is None
@skip_if_server_version_lt("2.6.0")
async def test_dump_and_restore(self, r: redis.Redis):
await r.set("a", "foo")
dumped = await r.dump("a")
await r.delete("a")
await r.restore("a", 0, dumped)
assert await r.get("a") == b"foo"
@skip_if_server_version_lt("3.0.0")
async def test_dump_and_restore_and_replace(self, r: redis.Redis):
await r.set("a", "bar")
dumped = await r.dump("a")
with pytest.raises(redis.ResponseError):
await r.restore("a", 0, dumped)
await r.restore("a", 0, dumped, replace=True)
assert await r.get("a") == b"bar"
@skip_if_server_version_lt("5.0.0")
async def test_dump_and_restore_absttl(self, r: redis.Redis):
await r.set("a", "foo")
dumped = await r.dump("a")
await r.delete("a")
ttl = int(
(await redis_server_time(r) + datetime.timedelta(minutes=1)).timestamp()
* 1000
)
await r.restore("a", ttl, dumped, absttl=True)
assert await r.get("a") == b"foo"
assert 0 < await r.ttl("a") <= 61
async def test_exists(self, r: redis.Redis):
assert await r.exists("a") == 0
await r.set("a", "foo")
await r.set("b", "bar")
assert await r.exists("a") == 1
assert await r.exists("a", "b") == 2
async def test_exists_contains(self, r: redis.Redis):
assert not await r.exists("a")
await r.set("a", "foo")
assert await r.exists("a")
async def test_expire(self, r: redis.Redis):
assert not await r.expire("a", 10)
await r.set("a", "foo")
assert await r.expire("a", 10)