-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
test_commands.py
3139 lines (2674 loc) · 117 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.client import EMPTY_RESPONSE, NEVER_DECODE, parse_info
from tests.conftest import (
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
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):
assert r.response_callbacks == redis.Redis.RESPONSE_CALLBACKS
assert id(r.response_callbacks) != id(redis.Redis.RESPONSE_CALLBACKS)
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["del"] == r.response_callbacks["DEL"]
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
@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
@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)
@skip_if_server_version_lt(REDIS_6_VERSION)
@skip_if_server_version_gte("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)
assert await r.acl_getuser(username) == {
"categories": ["-@all"],
"commands": [],
"channels": [b"*"],
"enabled": False,
"flags": ["off", "allchannels", "sanitize-payload"],
"keys": [],
"passwords": [],
}
# test nopass=True
assert await r.acl_setuser(username, enabled=True, reset=True, nopass=True)
assert await r.acl_getuser(username) == {
"categories": ["-@all"],
"commands": [],
"channels": [b"*"],
"enabled": True,
"flags": ["on", "allchannels", "nopass", "sanitize-payload"],
"keys": [],
"passwords": [],
}
# 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"}
assert set(acl["commands"]) == {"+get", "+mget", "-hset"}
assert acl["enabled"] is True
assert acl["channels"] == [b"*"]
assert acl["flags"] == ["on", "allchannels", "sanitize-payload"]
assert set(acl["keys"]) == {b"cache:*", b"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["categories"]) == {"-@all", "+@set", "+@hash"}
assert set(acl["commands"]) == {"+get", "+mget"}
assert acl["enabled"] is True
assert acl["channels"] == [b"*"]
assert acl["flags"] == ["on", "allchannels", "sanitize-payload"]
assert set(acl["keys"]) == {b"cache:*", b"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)
@skip_if_server_version_gte("7.0.0")
async def test_acl_list(self, r_teardown):
username = "redis-py-user"
r = r_teardown(username)
assert await r.acl_setuser(username, enabled=False, reset=True)
users = await r.acl_list()
assert f"user {username} off sanitize-payload &* -@all" in users
@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()) == 2
assert len(await r.acl_log(count=1)) == 1
assert isinstance((await r.acl_log())[0], dict)
assert "client-info" in (await r.acl_log(count=1))[0]
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)
@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 await r.client_getname() == "redis_py_test"
@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")
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.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)
assert 0 < await r.ttl("a") <= 10
assert await r.persist("a")
assert await r.ttl("a") == -1
async def test_expireat_datetime(self, r: redis.Redis):
expire_at = await redis_server_time(r) + datetime.timedelta(minutes=1)
await r.set("a", "foo")
assert await r.expireat("a", expire_at)
assert 0 < await r.ttl("a") <= 61
async def test_expireat_no_key(self, r: redis.Redis):
expire_at = await redis_server_time(r) + datetime.timedelta(minutes=1)
assert not await r.expireat("a", expire_at)
async def test_expireat_unixtime(self, r: redis.Redis):
expire_at = await redis_server_time(r) + datetime.timedelta(minutes=1)
await r.set("a", "foo")
expire_at_seconds = int(expire_at.timestamp())
assert await r.expireat("a", expire_at_seconds)
assert 0 < await r.ttl("a") <= 61
async def test_get_and_set(self, r: redis.Redis):
# 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_get_set_bit(self, r: redis.Redis):
# no value
assert not await r.getbit("a", 5)
# set bit 5
assert not await r.setbit("a", 5, True)
assert await r.getbit("a", 5)
# unset bit 4
assert not await r.setbit("a", 4, False)
assert not await r.getbit("a", 4)
# set bit 4
assert not await r.setbit("a", 4, True)
assert await r.getbit("a", 4)
# set bit 5 again
assert await r.setbit("a", 5, True)
assert await r.getbit("a", 5)
async def test_getrange(self, r: redis.Redis):
await r.set("a", "foo")
assert await r.getrange("a", 0, 0) == b"f"
assert await r.getrange("a", 0, 2) == b"foo"
assert await r.getrange("a", 3, 4) == b""
async def test_getset(self, r: redis.Redis):
assert await r.getset("a", "foo") is None
assert await r.getset("a", "bar") == b"foo"
assert await r.get("a") == b"bar"
async def test_incr(self, r: redis.Redis):
assert await r.incr("a") == 1
assert await r.get("a") == b"1"
assert await r.incr("a") == 2
assert await r.get("a") == b"2"
assert await r.incr("a", amount=5) == 7
assert await r.get("a") == b"7"
async def test_incrby(self, r: redis.Redis):
assert await r.incrby("a") == 1
assert await r.incrby("a", 4) == 5
assert await r.get("a") == b"5"
@skip_if_server_version_lt("2.6.0")
async def test_incrbyfloat(self, r: redis.Redis):
assert await r.incrbyfloat("a") == 1.0
assert await r.get("a") == b"1"
assert await r.incrbyfloat("a", 1.1) == 2.1
assert float(await r.get("a")) == float(2.1)
@pytest.mark.onlynoncluster
async def test_keys(self, r: redis.Redis):
assert await r.keys() == []
keys_with_underscores = {b"test_a", b"test_b"}
keys = keys_with_underscores.union({b"testc"})
for key in keys:
await r.set(key, 1)
assert set(await r.keys(pattern="test_*")) == keys_with_underscores
assert set(await r.keys(pattern="test*")) == keys
@pytest.mark.onlynoncluster
async def test_mget(self, r: redis.Redis):
assert await r.mget([]) == []
assert await r.mget(["a", "b"]) == [None, None]
await r.set("a", "1")
await r.set("b", "2")
await r.set("c", "3")
assert await r.mget("a", "other", "b", "c") == [b"1", None, b"2", b"3"]
@pytest.mark.onlynoncluster
async def test_mset(self, r: redis.Redis):
d = {"a": b"1", "b": b"2", "c": b"3"}
assert await r.mset(d)
for k, v in d.items():
assert await r.get(k) == v
@pytest.mark.onlynoncluster
async def test_msetnx(self, r: redis.Redis):
d = {"a": b"1", "b": b"2", "c": b"3"}
assert await r.msetnx(d)
d2 = {"a": b"x", "d": b"4"}
assert not await r.msetnx(d2)
for k, v in d.items():
assert await r.get(k) == v
assert await r.get("d") is None
@skip_if_server_version_lt("2.6.0")
async def test_pexpire(self, r: redis.Redis):
assert not await r.pexpire("a", 60000)
await r.set("a", "foo")
assert await r.pexpire("a", 60000)
assert 0 < await r.pttl("a") <= 60000
assert await r.persist("a")
assert await r.pttl("a") == -1
@skip_if_server_version_lt("2.6.0")
async def test_pexpireat_datetime(self, r: redis.Redis):
expire_at = await redis_server_time(r) + datetime.timedelta(minutes=1)
await r.set("a", "foo")
assert await r.pexpireat("a", expire_at)
assert 0 < await r.pttl("a") <= 61000
@skip_if_server_version_lt("2.6.0")
async def test_pexpireat_no_key(self, r: redis.Redis):
expire_at = await redis_server_time(r) + datetime.timedelta(minutes=1)
assert not await r.pexpireat("a", expire_at)
@skip_if_server_version_lt("2.6.0")
async def test_pexpireat_unixtime(self, r: redis.Redis):
expire_at = await redis_server_time(r) + datetime.timedelta(minutes=1)
await r.set("a", "foo")
expire_at_milliseconds = int(expire_at.timestamp() * 1000)
assert await r.pexpireat("a", expire_at_milliseconds)
assert 0 < await r.pttl("a") <= 61000
@skip_if_server_version_lt("2.6.0")
async def test_psetex(self, r: redis.Redis):
assert await r.psetex("a", 1000, "value")
assert await r.get("a") == b"value"
assert 0 < await r.pttl("a") <= 1000
@skip_if_server_version_lt("2.6.0")
async def test_psetex_timedelta(self, r: redis.Redis):
expire_at = datetime.timedelta(milliseconds=1000)
assert await r.psetex("a", expire_at, "value")
assert await r.get("a") == b"value"
assert 0 < await r.pttl("a") <= 1000
@skip_if_server_version_lt("2.6.0")
async def test_pttl(self, r: redis.Redis):
assert not await r.pexpire("a", 10000)
await r.set("a", "1")
assert await r.pexpire("a", 10000)
assert 0 < await r.pttl("a") <= 10000
assert await r.persist("a")
assert await r.pttl("a") == -1
@skip_if_server_version_lt("2.8.0")
async def test_pttl_no_key(self, r: redis.Redis):
"""PTTL on servers 2.8 and after return -2 when the key doesn't exist"""
assert await r.pttl("a") == -2
@pytest.mark.onlynoncluster
async def test_randomkey(self, r: redis.Redis):
assert await r.randomkey() is None
for key in ("a", "b", "c"):
await r.set(key, 1)
assert await r.randomkey() in (b"a", b"b", b"c")
@pytest.mark.onlynoncluster
async def test_rename(self, r: redis.Redis):
await r.set("a", "1")
assert await r.rename("a", "b")
assert await r.get("a") is None
assert await r.get("b") == b"1"
@pytest.mark.onlynoncluster
async def test_renamenx(self, r: redis.Redis):
await r.set("a", "1")
await r.set("b", "2")
assert not await r.renamenx("a", "b")
assert await r.get("a") == b"1"
assert await r.get("b") == b"2"
@skip_if_server_version_lt("2.6.0")
async def test_set_nx(self, r: redis.Redis):
assert await r.set("a", "1", nx=True)
assert not await r.set("a", "2", nx=True)
assert await r.get("a") == b"1"
@skip_if_server_version_lt("2.6.0")
async def test_set_xx(self, r: redis.Redis):
assert not await r.set("a", "1", xx=True)
assert await r.get("a") is None
await r.set("a", "bar")
assert await r.set("a", "2", xx=True)
assert await r.get("a") == b"2"
@skip_if_server_version_lt("2.6.0")
async def test_set_px(self, r: redis.Redis):
assert await r.set("a", "1", px=10000)
assert await r.get("a") == b"1"
assert 0 < await r.pttl("a") <= 10000
assert 0 < await r.ttl("a") <= 10
@skip_if_server_version_lt("2.6.0")
async def test_set_px_timedelta(self, r: redis.Redis):
expire_at = datetime.timedelta(milliseconds=1000)
assert await r.set("a", "1", px=expire_at)
assert 0 < await r.pttl("a") <= 1000
assert 0 < await r.ttl("a") <= 1
@skip_if_server_version_lt("2.6.0")
async def test_set_ex(self, r: redis.Redis):
assert await r.set("a", "1", ex=10)
assert 0 < await r.ttl("a") <= 10
@skip_if_server_version_lt("2.6.0")
async def test_set_ex_timedelta(self, r: redis.Redis):
expire_at = datetime.timedelta(seconds=60)
assert await r.set("a", "1", ex=expire_at)
assert 0 < await r.ttl("a") <= 60
@skip_if_server_version_lt("2.6.0")
async def test_set_multipleoptions(self, r: redis.Redis):
await r.set("a", "val")
assert await r.set("a", "1", xx=True, px=10000)
assert 0 < await r.ttl("a") <= 10
@skip_if_server_version_lt(REDIS_6_VERSION)
async def test_set_keepttl(self, r: redis.Redis):
await r.set("a", "val")
assert await r.set("a", "1", xx=True, px=10000)
assert 0 < await r.ttl("a") <= 10
await r.set("a", "2", keepttl=True)
assert await r.get("a") == b"2"
assert 0 < await r.ttl("a") <= 10