Skip to content

Commit a8b8f14

Browse files
authored
close socket after server disconnect (#1797)
1 parent 82bad16 commit a8b8f14

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

redis/connection.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -717,9 +717,14 @@ def disconnect(self):
717717
self._parser.on_disconnect()
718718
if self._sock is None:
719719
return
720-
try:
721-
if os.getpid() == self.pid:
720+
721+
if os.getpid() == self.pid:
722+
try:
722723
self._sock.shutdown(socket.SHUT_RDWR)
724+
except OSError:
725+
pass
726+
727+
try:
723728
self._sock.close()
724729
except OSError:
725730
pass

tests/test_connection.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
import pytest
55

6+
from redis.connection import Connection
67
from redis.exceptions import InvalidResponse
78
from redis.utils import HIREDIS_AVAILABLE
89

@@ -40,3 +41,36 @@ def inner():
4041
# mod = j(modclient)
4142
# mod.set("fookey", ".", d)
4243
# assert mod.get('fookey') == d
44+
45+
46+
class TestConnection:
47+
def test_disconnect(self):
48+
conn = Connection()
49+
mock_sock = mock.Mock()
50+
conn._sock = mock_sock
51+
conn.disconnect()
52+
mock_sock.shutdown.assert_called_once()
53+
mock_sock.close.assert_called_once()
54+
assert conn._sock is None
55+
56+
def test_disconnect__shutdown_OSError(self):
57+
"""An OSError on socket shutdown will still close the socket."""
58+
conn = Connection()
59+
mock_sock = mock.Mock()
60+
conn._sock = mock_sock
61+
conn._sock.shutdown.side_effect = OSError
62+
conn.disconnect()
63+
mock_sock.shutdown.assert_called_once()
64+
mock_sock.close.assert_called_once()
65+
assert conn._sock is None
66+
67+
def test_disconnect__close_OSError(self):
68+
"""An OSError on socket close will still clear out the socket."""
69+
conn = Connection()
70+
mock_sock = mock.Mock()
71+
conn._sock = mock_sock
72+
conn._sock.close.side_effect = OSError
73+
conn.disconnect()
74+
mock_sock.shutdown.assert_called_once()
75+
mock_sock.close.assert_called_once()
76+
assert conn._sock is None

0 commit comments

Comments
 (0)