|
1 | 1 | import asyncio
|
2 | 2 | import socket
|
3 | 3 | import types
|
4 |
| -from unittest.mock import patch |
| 4 | +from unittest.mock import Mock, patch |
5 | 5 |
|
6 | 6 | import pytest
|
7 | 7 | import redis
|
|
12 | 12 | _AsyncRESPBase,
|
13 | 13 | )
|
14 | 14 | from redis.asyncio import Redis
|
15 |
| -from redis.asyncio.connection import Connection, UnixDomainSocketConnection |
| 15 | +from redis.asyncio.connection import ( |
| 16 | + AbstractConnection, |
| 17 | + Connection, |
| 18 | + UnixDomainSocketConnection, |
| 19 | + parse_url, |
| 20 | +) |
16 | 21 | from redis.asyncio.retry import Retry
|
17 | 22 | from redis.backoff import NoBackoff
|
18 | 23 | from redis.exceptions import ConnectionError, InvalidResponse, TimeoutError
|
@@ -278,3 +283,45 @@ async def open_connection(*args, **kwargs):
|
278 | 283 | def test_create_single_connection_client_from_url():
|
279 | 284 | client = Redis.from_url("redis://localhost:6379/0?", single_connection_client=True)
|
280 | 285 | assert client.single_connection_client is True
|
| 286 | + |
| 287 | + |
| 288 | +@pytest.mark.parametrize("from_url", (True, False)) |
| 289 | +async def test_pool_auto_close(request, from_url): |
| 290 | + """Verify that basic Redis instances have auto_close_connection_pool set to True""" |
| 291 | + |
| 292 | + url: str = request.config.getoption("--redis-url") |
| 293 | + url_args = parse_url(url) |
| 294 | + |
| 295 | + async def get_redis_connection(): |
| 296 | + if from_url: |
| 297 | + return Redis.from_url(url) |
| 298 | + return Redis(**url_args) |
| 299 | + |
| 300 | + r1 = await get_redis_connection() |
| 301 | + assert r1.auto_close_connection_pool is True |
| 302 | + |
| 303 | + |
| 304 | +@pytest.mark.parametrize("from_url", (True, False)) |
| 305 | +async def test_connection_socket_cleanup(request, from_url): |
| 306 | + """Verify that connections are cleaned up when they |
| 307 | + are garbage collected |
| 308 | + """ |
| 309 | + url: str = request.config.getoption("--redis-url") |
| 310 | + url_args = parse_url(url) |
| 311 | + |
| 312 | + async def get_redis_connection(): |
| 313 | + if from_url: |
| 314 | + return Redis.from_url(url) |
| 315 | + return Redis(**url_args) |
| 316 | + |
| 317 | + async def do_something(redis): |
| 318 | + await redis.incr("counter") |
| 319 | + await redis.close() |
| 320 | + |
| 321 | + mock = Mock() |
| 322 | + with patch.object(AbstractConnection, "_close_socket", mock): |
| 323 | + r1 = await get_redis_connection() |
| 324 | + await do_something(r1) |
| 325 | + r1 = None |
| 326 | + |
| 327 | + assert mock.call_count == 1 |
0 commit comments