Debian Codegraph @

tests/unittests/test_client.py

raw
1 import os
2 import re
3 from textwrap import dedent
4 from unittest.mock import MagicMock, patch
5
6 from packaging.version import parse as version_parse
7 from prompt_toolkit.formatted_text import FormattedText
8 import pytest
9 import redis
10
11 from iredis.client import Client
12 from iredis.commands import command2syntax
13 from iredis.completers import IRedisCompleter
14 from iredis.config import config, load_config_files
15 from iredis.entry import Rainbow, prompt_message
16 from iredis.exceptions import NotSupport
17
18 from ..helpers import formatted_text_rematch
19
20
21 @pytest.fixture
22 def completer():
23 return IRedisCompleter()
24
25
26 zset_type = "ziplist"
27 hash_type = "hashtable"
28 list_type = "quicklist"
29 if version_parse(os.environ.get("REDIS_VERSION", "0")) >= version_parse("7"):
30 zset_type = "listpack"
31 hash_type = "listpack"
32 list_type = "listpack"
33
34
35 @pytest.mark.parametrize(
36 "_input, command_name, expect_args",
37 [
38 ("keys *", "keys", ["*"]),
39 ("DEL abc foo bar", "DEL", ["abc", "foo", "bar"]),
40 ("cluster info", "cluster info", []),
41 ("CLUSTER failover FORCE", "CLUSTER failover", ["FORCE"]),
42 ],
43 )
44 def test_send_command(_input, command_name, expect_args):
45 client = Client("127.0.0.1", 6379, None)
46 client.execute = MagicMock()
47 next(client.send_command(_input, None))
48 args, _ = client.execute.call_args
49 assert args == (command_name, *expect_args)
50
51
52 def test_client_not_support_hello_command(iredis_client):
53 with pytest.raises(NotSupport):
54 iredis_client.pre_hook("hello 3", "hello", "3", None)
55
56
57 def test_patch_completer():
58 client = Client("127.0.0.1", "6379", None)
59 completer = IRedisCompleter()
60 client.pre_hook(
61 "MGET foo bar hello world", "MGET", "foo bar hello world", completer
62 )
63 assert completer.key_completer.words == ["world", "hello", "bar", "foo"]
64 assert completer.key_completer.words == ["world", "hello", "bar", "foo"]
65
66 client.pre_hook("GET bar", "GET", "bar", completer)
67 assert completer.key_completer.words == ["bar", "world", "hello", "foo"]
68
69
70 def test_get_server_verison_after_client(config):
71 Client("127.0.0.1", "6379", None)
72 assert re.match(r"\d+\..*", config.version)
73
74 config.version = "Unknown"
75 config.no_info = True
76 Client("127.0.0.1", "6379", None)
77 assert config.version == "Unknown"
78
79
80 def test_do_help(config):
81 client = Client("127.0.0.1", "6379", None)
82 config.version = "5.0.0"
83 resp = client.do_help("SET")
84 assert resp[10] == ("", "1.0.0 (Available on your redis-server: 5.0.0)")
85 config.version = "2.0.0"
86 resp = client.do_help("cluster", "addslots")
87 assert resp[10] == ("", "3.0.0 (Not available on your redis-server: 2.0.0)")
88
89
90 def test_rainbow_iterator():
91 "test color infinite iterator"
92 original_color = Rainbow.color
93 Rainbow.color = list(range(0, 3))
94 assert list(zip(range(10), Rainbow())) == [
95 (0, 0),
96 (1, 1),
97 (2, 2),
98 (3, 1),
99 (4, 0),
100 (5, 1),
101 (6, 2),
102 (7, 1),
103 (8, 0),
104 (9, 1),
105 ]
106 Rainbow.color = original_color
107
108
109 def test_prompt_message(iredis_client, config):
110 config.rainbow = False
111 assert prompt_message(iredis_client) == "127.0.0.1:6379[15]> "
112
113 config.rainbow = True
114 assert prompt_message(iredis_client)[:3] == [
115 ("#cc2244", "1"),
116 ("#bb4444", "2"),
117 ("#996644", "7"),
118 ]
119
120
121 def test_on_connection_error_retry(iredis_client, config):
122 config.retry_times = 1
123 mock_connection = MagicMock()
124 mock_connection.read_response.side_effect = [
125 redis.exceptions.ConnectionError(
126 "Error 61 connecting to 127.0.0.1:7788. Connection refused."
127 ),
128 "hello",
129 ]
130 original_connection = iredis_client.connection
131 iredis_client.connection = mock_connection
132 value = iredis_client.execute("None", "GET", ["foo"])
133 assert value == "hello" # be rendered
134
135 mock_connection.disconnect.assert_called_once()
136 mock_connection.connect.assert_called_once()
137
138 iredis_client.connection = original_connection
139
140
141 def test_on_connection_error_retry_without_retrytimes(iredis_client, config):
142 config.retry_times = 0
143 mock_connection = MagicMock()
144 mock_connection.read_response.side_effect = [
145 redis.exceptions.ConnectionError(
146 "Error 61 connecting to 127.0.0.1:7788. Connection refused."
147 ),
148 "hello",
149 ]
150 iredis_client.connection = mock_connection
151 with pytest.raises(redis.exceptions.ConnectionError):
152 iredis_client.execute("None", "GET", ["foo"])
153
154 mock_connection.disconnect.assert_not_called()
155 mock_connection.connect.assert_not_called()
156
157
158 def test_socket_keepalive(config):
159 config.socket_keepalive = True
160 from iredis.client import Client
161
162 newclient = Client("127.0.0.1", "6379", 0)
163 assert newclient.connection.socket_keepalive
164
165 # keepalive off
166 config.socket_keepalive = False
167
168 newclient = Client("127.0.0.1", "6379", 0)
169 assert not newclient.connection.socket_keepalive
170
171
172 def test_not_retry_on_authentication_error(iredis_client, config):
173 config.retry_times = 2
174 mock_connection = MagicMock()
175 mock_connection.read_response.side_effect = [
176 redis.exceptions.AuthenticationError("Authentication required."),
177 "hello",
178 ]
179 iredis_client.connection = mock_connection
180 with pytest.raises(redis.exceptions.ConnectionError):
181 iredis_client.execute("None", "GET", ["foo"])
182
183
184 @pytest.mark.skipif(
185 "version_parse(os.environ.get('REDIS_VERSION', '0')) != version_parse('6')",
186 reason="""
187 in redis7, it will not work if you:
188 1. connect redis without password
189 2. set a password
190 3. auth
191
192 the auth will fail""",
193 )
194 def test_auto_select_db_and_auth_for_reconnect_only_6(iredis_client, config):
195 config.retry_times = 2
196 config.raw = True
197 next(iredis_client.send_command("select 2"))
198 assert iredis_client.connection.db == 2
199
200 resp = next(iredis_client.send_command("auth 123"))
201
202 assert (
203 b"ERROR AUTH <password> called without any "
204 b"password configured for the default user. "
205 b"Are you sure your configuration is correct?" in resp
206 )
207 assert iredis_client.connection.password is None
208
209 next(iredis_client.send_command("config set requirepass 'abc'"))
210 next(iredis_client.send_command("auth abc"))
211 assert iredis_client.connection.password == "abc"
212 assert (
213 iredis_client.execute("ACL SETUSER", "default", "on", "nopass", "~*", "+@all")
214 == b"OK"
215 )
216
217
218 @pytest.mark.skipif(
219 "version_parse(os.environ.get('REDIS_VERSION', '0')) > version_parse('5')"
220 )
221 def test_auto_select_db_and_auth_for_reconnect_only_5(iredis_client, config):
222 config.retry_times = 2
223 config.raw = True
224 next(iredis_client.send_command("select 2"))
225 assert iredis_client.connection.db == 2
226
227 resp = next(iredis_client.send_command("auth 123"))
228
229 assert b"Client sent AUTH, but no password is set" in resp
230 assert iredis_client.connection.password is None
231
232 next(iredis_client.send_command("config set requirepass 'abc'"))
233 next(iredis_client.send_command("auth abc"))
234 assert iredis_client.connection.password == "abc"
235 next(iredis_client.send_command("config set requirepass ''"))
236
237
238 def test_split_shell_command(iredis_client, completer):
239 assert iredis_client.split_command_and_pipeline(" get json | rg . ", completer) == (
240 " get json ",
241 "rg . ",
242 )
243
244 assert iredis_client.split_command_and_pipeline(
245 """ get "json | \\" hello" | rg . """, completer
246 ) == (""" get "json | \\" hello" """, "rg . ")
247
248
249 def test_running_with_pipeline(clean_redis, iredis_client, capfd, completer):
250 config.shell = True
251 clean_redis.set("foo", "hello \n world")
252 with pytest.raises(StopIteration):
253 next(iredis_client.send_command("get foo | grep w", completer))
254 out, err = capfd.readouterr()
255 assert out == " world\n"
256
257
258 def test_running_with_multiple_pipeline(clean_redis, iredis_client, capfd, completer):
259 config.shell = True
260 clean_redis.set("foo", "hello world\nhello iredis")
261 with pytest.raises(StopIteration):
262 next(
263 iredis_client.send_command("get foo | grep hello | grep iredis", completer)
264 )
265 out, err = capfd.readouterr()
266 assert out == "hello iredis\n"
267
268
269 def test_can_not_connect_on_startup(capfd):
270 with pytest.raises(SystemExit):
271 Client("localhost", "16111", 15)
272 out, err = capfd.readouterr()
273 assert "connecting to localhost:16111." in err
274
275
276 def test_peek_key_not_exist(iredis_client, clean_redis, config):
277 config.raw = False
278 peek_result = list(iredis_client.do_peek("non-exist-key"))
279 assert peek_result == ["non-exist-key doesn't exist."]
280
281
282 def test_iredis_with_username():
283 with patch("redis.connection.Connection.connect"):
284 c = Client("127.0.0.1", "6379", username="abc", password="abc1")
285 assert c.connection.username == "abc"
286 assert c.connection.password == "abc1"
287
288
289 def test_peek_string(iredis_client, clean_redis):
290 clean_redis.set("foo", "bar")
291 peek_result = list(iredis_client.do_peek("foo"))
292
293 assert peek_result[0][0] == ("class:dockey", "key: ")
294 assert re.match(r"string \(embstr\) mem: \d+ bytes, ttl: -1", peek_result[0][1][1])
295 assert peek_result[0][2:] == [
296 ("", "\n"),
297 ("class:dockey", "strlen: "),
298 ("", "3"),
299 ("", "\n"),
300 ("class:dockey", "value: "),
301 ("", '"bar"'),
302 ]
303
304
305 def test_peek_list_fetch_all(iredis_client, clean_redis):
306 clean_redis.lpush("mylist", *[f"hello-{index}" for index in range(5)])
307 peek_result = list(iredis_client.do_peek("mylist"))
308
309 formatted_text_rematch(
310 peek_result[0],
311 FormattedText(
312 [
313 ("class:dockey", "key: "),
314 ("", rf"list \({list_type}\) mem: \d+ bytes, ttl: -1"),
315 ("", "\n"),
316 ("class:dockey", "llen: "),
317 ("", "5"),
318 ("", "\n"),
319 ("class:dockey", "elements: "),
320 ("", "\n"),
321 ("", r"1\)"),
322 ("", " "),
323 ("class:string", '"hello-4"'),
324 ("", "\n"),
325 ("", r"2\)"),
326 ("", " "),
327 ("class:string", '"hello-3"'),
328 ("", "\n"),
329 ("", r"3\)"),
330 ("", " "),
331 ("class:string", '"hello-2"'),
332 ("", "\n"),
333 ("", r"4\)"),
334 ("", " "),
335 ("class:string", '"hello-1"'),
336 ("", "\n"),
337 ("", r"5\)"),
338 ("", " "),
339 ("class:string", '"hello-0"'),
340 ]
341 ),
342 )
343
344
345 def test_peek_list_fetch_part(iredis_client, clean_redis):
346 clean_redis.lpush("mylist", *[f"hello-{index}" for index in range(40)])
347 peek_result = list(iredis_client.do_peek("mylist"))
348 assert len(peek_result[0]) == 91
349
350
351 def test_peek_set_fetch_all(iredis_client, clean_redis):
352 clean_redis.sadd("myset", *[f"hello-{index}" for index in range(5)])
353 peek_result = list(iredis_client.do_peek("myset"))
354 assert len(peek_result[0]) == 27
355
356
357 def test_peek_set_fetch_part(iredis_client, clean_redis):
358 clean_redis.sadd("myset", *[f"hello-{index}" for index in range(40)])
359 peek_result = list(iredis_client.do_peek("myset"))
360
361 assert peek_result[0][0] == ("class:dockey", "key: ")
362 assert peek_result[0][1][1].startswith(f"set ({hash_type}) mem: ")
363
364
365 def test_peek_zset_fetch_all(iredis_client, clean_redis):
366 clean_redis.zadd(
367 "myzset", dict(zip([f"hello-{index}" for index in range(3)], range(3)))
368 )
369 peek_result = list(iredis_client.do_peek("myzset"))
370
371 formatted_text_rematch(
372 peek_result[0][0:9],
373 FormattedText(
374 [
375 ("class:dockey", "key: "),
376 ("", rf"zset \({zset_type}\) mem: \d+ bytes, ttl: -1"),
377 ("", "\n"),
378 ("class:dockey", "zcount: "),
379 ("", "3"),
380 ("", "\n"),
381 ("class:dockey", "members: "),
382 ("", "\n"),
383 ("", r"1\)"),
384 ]
385 ),
386 )
387
388
389 def test_peek_zset_fetch_part(iredis_client, clean_redis):
390 clean_redis.zadd(
391 "myzset", dict(zip([f"hello-{index}" for index in range(40)], range(40)))
392 )
393 peek_result = list(iredis_client.do_peek("myzset"))
394 formatted_text_rematch(
395 peek_result[0][0:8],
396 FormattedText(
397 [
398 ("class:dockey", "key: "),
399 ("", rf"zset \({zset_type}\) mem: \d+ bytes, ttl: -1"),
400 ("", "\n"),
401 ("class:dockey", "zcount: "),
402 ("", "40"),
403 ("", "\n"),
404 ("class:dockey", r"members \(first 40\): "),
405 ("", "\n"),
406 ]
407 ),
408 )
409
410
411 def test_peek_hash_fetch_all(iredis_client, clean_redis):
412 for key, value in zip(
413 [f"hello-{index}" for index in range(3)], [f"hi-{index}" for index in range(3)]
414 ):
415 clean_redis.hset("myhash", key, value)
416 peek_result = list(iredis_client.do_peek("myhash"))
417 assert len(peek_result[0]) == 28
418
419
420 def test_peek_hash_fetch_part(iredis_client, clean_redis):
421 for key, value in zip(
422 [f"hello-{index}" for index in range(100)],
423 [f"hi-{index}" for index in range(100)],
424 ):
425 clean_redis.hset("myhash", key, value)
426 peek_result = list(iredis_client.do_peek("myhash"))
427 assert len(peek_result[0]) == 707
428
429
430 def test_peek_stream(iredis_client, clean_redis):
431 clean_redis.xadd("mystream", {"foo": "bar", "hello": "world"})
432 peek_result = list(iredis_client.do_peek("mystream"))
433
434 assert peek_result[0][0] == ("class:dockey", "key: ")
435 assert re.match(
436 r"stream \((stream|unknown)\) mem: \d+ bytes, ttl: -1", peek_result[0][1][1]
437 )
438 assert peek_result[0][2:18] == FormattedText(
439 [
440 ("", "\n"),
441 ("class:dockey", "XINFO: "),
442 ("", "\n"),
443 ("", " 1)"),
444 ("", " "),
445 ("class:string", '"length"'),
446 ("", "\n"),
447 ("", " 2)"),
448 ("", " "),
449 ("class:string", '"1"'),
450 ("", "\n"),
451 ("", " 3)"),
452 ("", " "),
453 ("class:string", '"radix-tree-keys"'),
454 ("", "\n"),
455 ("", " 4)"),
456 ]
457 )
458
459
460 def test_mem_not_called_before_redis_4(config, iredis_client, clean_redis):
461 config.version = "3.2.9"
462
463 def wrapper(func):
464 def execute(command_name, *args):
465 print(command_name)
466 if command_name.upper() == "MEMORY USAGE":
467 raise Exception("MEMORY USAGE not supported!")
468 return func(command_name, *args)
469
470 return execute
471
472 iredis_client.execute = wrapper(iredis_client.execute)
473 clean_redis.set("foo", "bar")
474 result = list(iredis_client.do_peek("foo"))
475 assert result[0][1] == ("", "string (embstr), ttl: -1")
476
477
478 def test_mem_not_called_when_cant_get_server_version(
479 config, iredis_client, clean_redis
480 ):
481 config.version = None
482
483 def wrapper(func):
484 def execute(command_name, *args):
485 print(command_name)
486 if command_name.upper() == "MEMORY USAGE":
487 raise Exception("MEMORY USAGE not supported!")
488 return func(command_name, *args)
489
490 return execute
491
492 iredis_client.execute = wrapper(iredis_client.execute)
493 clean_redis.set("foo", "bar")
494 result = list(iredis_client.do_peek("foo"))
495 assert result[0][1] == ("", "string (embstr), ttl: -1")
496
497
498 def test_reissue_command_on_redis_cluster_on_old_redispy(iredis_client, clean_redis):
499 # In redis<6, MOVED errors caused ResponseError instead of MovedError to be raised
500 mock_response = iredis_client.connection = MagicMock()
501 mock_response.read_response.side_effect = redis.exceptions.ResponseError(
502 "MOVED 12182 127.0.0.1:7002"
503 )
504 iredis_client.reissue_with_redirect = MagicMock()
505 iredis_client.execute("set", "foo", "bar")
506 assert iredis_client.reissue_with_redirect.call_args == (
507 (
508 "MOVED 12182 127.0.0.1:7002",
509 "set",
510 "foo",
511 "bar",
512 ),
513 )
514
515
516 def test_reissue_command_on_redis_cluster(iredis_client, clean_redis):
517 mock_response = iredis_client.connection = MagicMock()
518 mock_response.read_response.side_effect = redis.exceptions.MovedError(
519 "12182 127.0.0.1:7002"
520 )
521 iredis_client.reissue_with_redirect = MagicMock()
522 iredis_client.execute("set", "foo", "bar")
523 assert iredis_client.reissue_with_redirect.call_args == (
524 (
525 "MOVED 12182 127.0.0.1:7002",
526 "set",
527 "foo",
528 "bar",
529 ),
530 )
531
532
533 def test_reissue_command_on_redis_cluster_with_password_in_dsn(
534 iredis_client, clean_redis
535 ):
536 config_content = dedent(
537 """
538 [main]
539 log_location = /tmp/iredis1.log
540 no_info=True
541 [alias_dsn]
542 cluster-7003=redis://foo:[email protected]:7003
543 """
544 )
545 with open("/tmp/iredisrc", "w+") as etc_config:
546 etc_config.write(config_content)
547
548 config_obj = load_config_files("/tmp/iredisrc")
549 config.alias_dsn = config_obj["alias_dsn"]
550
551 mock_execute_by_connection = iredis_client.execute_by_connection = MagicMock()
552 with patch("redis.connection.Connection.connect"):
553 iredis_client.reissue_with_redirect(
554 "MOVED 12182 127.0.0.1:7003", "set", "foo", "bar"
555 )
556
557 call_args = mock_execute_by_connection.call_args[0]
558 print(call_args)
559 assert list(call_args[1:]) == ["set", "foo", "bar"]
560 assert call_args[0].password == "bar"
561
562
563 def test_reissue_command_on_redis_cluster_with_natmap(iredis_client, clean_redis):
564 config.natmap = {"192.168.1.1:6379": ("127.0.0.1", 6371)}
565
566 mock_execute_by_connection = iredis_client.execute_by_connection = MagicMock()
567 with patch("redis.connection.Connection.connect"):
568 iredis_client.reissue_with_redirect(
569 "MOVED 12182 192.168.1.1:6379", "set", "foo", "bar"
570 )
571
572 call_args = mock_execute_by_connection.call_args[0]
573 assert call_args[0].host == "127.0.0.1"
574 assert call_args[0].port == 6371
575
576 config.natmap = {}
577
578
579 def test_version_parse_for_auth(iredis_client):
580 """
581 fix: https://github.com/laixintao/iredis/issues/418
582 """
583 iredis_client.auth_compat("6.1.0")
584 assert command2syntax["AUTH"] == "command_usernamex_password"
585 iredis_client.auth_compat("5.0")
586 assert command2syntax["AUTH"] == "command_password"
587 iredis_client.auth_compat("5.0.14.1")
588 assert command2syntax["AUTH"] == "command_password"
589
590
591 @pytest.mark.parametrize(
592 "info, version",
593 [
594 (
595 (
596 "# Server\r\nredis_version:df--128-NOTFOUND\r\n"
597 "redis_mode:standalone\r\narch_bits:64"
598 ),
599 "df--128-NOTFOUND",
600 ),
601 (
602 (
603 "# Server\r\nredis_version:6.2.5\r\n"
604 "redis_git_sha1:00000000\r\n"
605 "redis_git_dirty:0\r\n"
606 "redis_build_id:915e5480613bc9b6\r\n"
607 "redis_mode:standalone "
608 ),
609 "6.2.5",
610 ),
611 (
612 (
613 "# Server\r\nredis_version:5.0.14.1\r\n"
614 "redis_git_sha1:00000000\r\nredis_git_dirty:0\r\n"
615 "redis_build_id:915e5480613bc9b6\r\n"
616 "redis_mode:standalone "
617 ),
618 "5.0.14.1",
619 ),
620 ],
621 )
622 def test_version_path(info, version):
623 with patch("iredis.client.config") as mock_config:
624 mock_config.no_info = True
625 mock_config.pager = "less"
626 mock_config.version = "5.0.0"
627 mock_config.decode = "utf-8"
628 with patch("iredis.client.Client.execute") as mock_execute:
629 mock_execute.return_value = info
630 client = Client("127.0.0.1", 6379)
631 client.get_server_info()
632 assert mock_config.version == version
633
634
635 def test_prompt():
636 c = Client()
637 assert str(c) == "127.0.0.1:6379> "
638
639 c = Client(prompt="{host} {port} {db}")
640 assert str(c) == "127.0.0.1 6379 0"
641
642 c = Client(prompt="{host} {port} {db} {username}")
643 assert str(c) == "127.0.0.1 6379 0 None"
644
645 c = Client(prompt="{host} {port} {db} {username}", username="foo1")
646 assert str(c) == "127.0.0.1 6379 0 foo1"
647
648 c = Client(prompt="{client_id} aabc")
649 assert re.match(r"^\d+ aabc$", str(c))
650 c = Client(prompt="{client_addr} >")
651 assert re.match(r"^127.0.0.1:\d+ >$", str(c))