|
| 1 | +import socket |
1 | 2 | import types
|
2 | 3 | from unittest import mock
|
| 4 | +from unittest.mock import patch |
3 | 5 |
|
4 | 6 | import pytest
|
5 | 7 |
|
| 8 | +from redis.backoff import NoBackoff |
6 | 9 | from redis.connection import Connection
|
7 |
| -from redis.exceptions import InvalidResponse |
| 10 | +from redis.exceptions import ConnectionError, InvalidResponse, TimeoutError |
| 11 | +from redis.retry import Retry |
8 | 12 | from redis.utils import HIREDIS_AVAILABLE
|
9 | 13 |
|
10 | 14 | from .conftest import skip_if_server_version_lt
|
@@ -74,3 +78,47 @@ def test_disconnect__close_OSError(self):
|
74 | 78 | mock_sock.shutdown.assert_called_once()
|
75 | 79 | mock_sock.close.assert_called_once()
|
76 | 80 | assert conn._sock is None
|
| 81 | + |
| 82 | + def clear(self, conn): |
| 83 | + conn.retry_on_error.clear() |
| 84 | + |
| 85 | + def test_retry_connect_on_timeout_error(self): |
| 86 | + """Test that the _connect function is retried in case of a timeout""" |
| 87 | + conn = Connection(retry_on_timeout=True, retry=Retry(NoBackoff(), 3)) |
| 88 | + origin_connect = conn._connect |
| 89 | + conn._connect = mock.Mock() |
| 90 | + |
| 91 | + def mock_connect(): |
| 92 | + # connect only on the last retry |
| 93 | + if conn._connect.call_count <= 2: |
| 94 | + raise socket.timeout |
| 95 | + else: |
| 96 | + return origin_connect() |
| 97 | + |
| 98 | + conn._connect.side_effect = mock_connect |
| 99 | + conn.connect() |
| 100 | + assert conn._connect.call_count == 3 |
| 101 | + self.clear(conn) |
| 102 | + |
| 103 | + def test_connect_without_retry_on_os_error(self): |
| 104 | + """Test that the _connect function is not being retried in case of a OSError""" |
| 105 | + with patch.object(Connection, "_connect") as _connect: |
| 106 | + _connect.side_effect = OSError("") |
| 107 | + conn = Connection(retry_on_timeout=True, retry=Retry(NoBackoff(), 2)) |
| 108 | + with pytest.raises(ConnectionError): |
| 109 | + conn.connect() |
| 110 | + assert _connect.call_count == 1 |
| 111 | + self.clear(conn) |
| 112 | + |
| 113 | + def test_connect_timeout_error_without_retry(self): |
| 114 | + """Test that the _connect function is not being retried if retry_on_timeout is |
| 115 | + set to False""" |
| 116 | + conn = Connection(retry_on_timeout=False) |
| 117 | + conn._connect = mock.Mock() |
| 118 | + conn._connect.side_effect = socket.timeout |
| 119 | + |
| 120 | + with pytest.raises(TimeoutError) as e: |
| 121 | + conn.connect() |
| 122 | + assert conn._connect.call_count == 1 |
| 123 | + assert str(e.value) == "Timeout connecting to server" |
| 124 | + self.clear(conn) |
0 commit comments