Skip to content

Commit aacf705

Browse files
committed
Normalize to using mock.mock everywhere instead of mixing and matching.
1 parent 91b2344 commit aacf705

21 files changed

+73
-91
lines changed

dev_requirements.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ flake8-isort
55
flake8
66
flynt~=0.69.0
77
invoke==2.2.0
8-
mock
8+
mock~=5.1.0
99
packaging>=20.4
1010
pytest
1111
pytest-asyncio>=0.23.0,<0.24.0

tests/conftest.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,11 @@
66
from datetime import datetime, timezone
77
from enum import Enum
88
from typing import Callable, TypeVar, Union
9-
from unittest import mock
10-
from unittest.mock import Mock
119
from urllib.parse import urlparse
1210

1311
import pytest
1412
import redis
13+
from mock.mock import Mock, patch
1514
from packaging.version import Version
1615
from redis import Sentinel
1716
from redis.auth.idp import IdentityProviderInterface
@@ -510,7 +509,7 @@ def _gen_cluster_mock_resp(r, response):
510509
connection = Mock(spec=Connection)
511510
connection.retry = Retry(NoBackoff(), 0)
512511
connection.read_response.return_value = response
513-
with mock.patch.object(r, "connection", connection):
512+
with patch.object(r, "connection", connection):
514513
yield r
515514

516515

tests/test_asyncio/compat.py

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,3 @@
1-
import asyncio
2-
from unittest import mock
3-
4-
try:
5-
mock.AsyncMock
6-
except AttributeError:
7-
from unittest import mock
8-
91
try:
102
from contextlib import aclosing
113
except ImportError:
@@ -17,7 +9,3 @@ async def aclosing(thing):
179
yield thing
1810
finally:
1911
await thing.aclose()
20-
21-
22-
def create_task(coroutine):
23-
return asyncio.create_task(coroutine)

tests/test_asyncio/conftest.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import pytest
88
import pytest_asyncio
99
import redis.asyncio as redis
10-
from mock.mock import Mock
10+
from mock.mock import AsyncMock, Mock, patch
1111
from packaging.version import Version
1212
from redis.asyncio import Sentinel
1313
from redis.asyncio.client import Monitor
@@ -36,8 +36,6 @@
3636
)
3737
from tests.conftest import REDIS_INFO
3838

39-
from .compat import mock
40-
4139

4240
class AuthType(Enum):
4341
MANAGED_IDENTITY = "managed_identity"
@@ -171,10 +169,10 @@ async def master(request, sentinel_setup):
171169

172170

173171
def _gen_cluster_mock_resp(r, response):
174-
connection = mock.AsyncMock(spec=Connection)
172+
connection = AsyncMock(spec=Connection)
175173
connection.retry = Retry(NoBackoff(), 0)
176174
connection.read_response.return_value = response
177-
with mock.patch.object(r, "connection", connection):
175+
with patch.object(r, "connection", connection):
178176
yield r
179177

180178

tests/test_asyncio/test_cluster.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import pytest
1010
import pytest_asyncio
1111
from _pytest.fixtures import FixtureRequest
12+
from mock import mock
1213
from redis._parsers import AsyncCommandsParser
1314
from redis.asyncio.cluster import ClusterNode, NodesManager, RedisCluster
1415
from redis.asyncio.connection import Connection, SSLConnection, async_timeout
@@ -38,7 +39,7 @@
3839
)
3940

4041
from ..ssl_utils import get_tls_certificates
41-
from .compat import aclosing, mock
42+
from .compat import aclosing
4243

4344
pytestmark = pytest.mark.onlycluster
4445

tests/test_asyncio/test_connection.py

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22
import socket
33
import types
44
from errno import ECONNREFUSED
5-
from unittest.mock import patch
65

76
import pytest
87
import redis
8+
from mock import mock
99
from redis._parsers import (
1010
_AsyncHiredisParser,
1111
_AsyncRESP2Parser,
@@ -25,7 +25,6 @@
2525
from redis.utils import HIREDIS_AVAILABLE
2626
from tests.conftest import skip_if_server_version_lt
2727

28-
from .compat import mock
2928
from .mocks import MockStream
3029

3130

@@ -43,7 +42,7 @@ async def test_invalid_response(create_redis):
4342
else:
4443
exp_err = f'Protocol error, got "{raw.decode()}" as reply type byte'
4544

46-
with mock.patch.object(parser, "_stream", fake_stream):
45+
with mock.mock.patch.object(parser, "_stream", fake_stream):
4746
with pytest.raises(InvalidResponse, match=exp_err):
4847
await parser.read_response()
4948

@@ -86,8 +85,8 @@ async def get_conn():
8685
init_call_count += 1
8786
return mock_conn
8887

89-
with mock.patch.object(r.connection_pool, "get_connection", get_conn):
90-
with mock.patch.object(r.connection_pool, "release"):
88+
with mock.mock.patch.object(r.connection_pool, "get_connection", get_conn):
89+
with mock.mock.patch.object(r.connection_pool, "release"):
9190
await asyncio.gather(r.set("a", "b"), r.set("c", "d"))
9291

9392
assert init_call_count == 1
@@ -157,7 +156,7 @@ async def mock_connect():
157156

158157
async def test_connect_without_retry_on_os_error():
159158
"""Test that the _connect function is not being retried in case of a OSError"""
160-
with patch.object(Connection, "_connect") as _connect:
159+
with mock.patch.object(Connection, "_connect") as _connect:
161160
_connect.side_effect = OSError("")
162161
conn = Connection(retry_on_timeout=True, retry=Retry(NoBackoff(), 2))
163162
with pytest.raises(ConnectionError):
@@ -281,9 +280,9 @@ async def dummy_method(*args, **kwargs):
281280
pass
282281

283282
# get dummy stream objects for the connection
284-
with patch.object(asyncio, "open_connection", open_connection):
283+
with mock.patch.object(asyncio, "open_connection", open_connection):
285284
# disable the initial version handshake
286-
with patch.multiple(
285+
with mock.patch.multiple(
287286
conn, send_command=dummy_method, read_response=dummy_method
288287
):
289288
await conn.connect()
@@ -325,7 +324,7 @@ async def mock_aclose(self):
325324

326325
url: str = request.config.getoption("--redis-url")
327326
r1 = await Redis.from_url(url)
328-
with patch.object(r1, "aclose", mock_aclose):
327+
with mock.patch.object(r1, "aclose", mock_aclose):
329328
with pytest.deprecated_call():
330329
await r1.close()
331330
assert calls == 1
@@ -382,7 +381,7 @@ async def mock_disconnect(_):
382381
nonlocal called
383382
called += 1
384383

385-
with patch.object(ConnectionPool, "disconnect", mock_disconnect):
384+
with mock.patch.object(ConnectionPool, "disconnect", mock_disconnect):
386385
async with await get_redis_connection() as r1:
387386
assert r1.auto_close_connection_pool is False
388387

@@ -414,7 +413,7 @@ async def mock_disconnect(_):
414413
nonlocal called
415414
called += 1
416415

417-
with patch.object(ConnectionPool, "disconnect", mock_disconnect):
416+
with mock.patch.object(ConnectionPool, "disconnect", mock_disconnect):
418417
async with await get_redis_connection() as r1:
419418
assert r1.auto_close_connection_pool is True
420419

@@ -441,7 +440,7 @@ async def mock_disconnect(_):
441440
nonlocal called
442441
called += 1
443442

444-
with patch.object(ConnectionPool, "disconnect", mock_disconnect):
443+
with mock.patch.object(ConnectionPool, "disconnect", mock_disconnect):
445444
async with await get_redis_connection() as r1:
446445
assert r1.auto_close_connection_pool is False
447446

@@ -461,7 +460,7 @@ async def test_client_garbage_collection(request):
461460
# create a client with a connection from the pool
462461
client = Redis(connection_pool=pool, single_connection_client=True)
463462
await client.initialize()
464-
with mock.patch.object(client, "connection") as a:
463+
with mock.mock.patch.object(client, "connection") as a:
465464
# we cannot, in unittests, or from asyncio, reliably trigger garbage collection
466465
# so we must just invoke the handler
467466
with pytest.warns(ResourceWarning):
@@ -486,8 +485,8 @@ async def test_connection_garbage_collection(request):
486485
await client.initialize()
487486
conn = client.connection
488487

489-
with mock.patch.object(conn, "_reader"):
490-
with mock.patch.object(conn, "_writer") as a:
488+
with mock.mock.patch.object(conn, "_reader"):
489+
with mock.mock.patch.object(conn, "_writer") as a:
491490
# we cannot, in unittests, or from asyncio, reliably trigger
492491
# garbage collection so we must just invoke the handler
493492
with pytest.warns(ResourceWarning):

tests/test_asyncio/test_connection_pool.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,12 @@
55
import pytest
66
import pytest_asyncio
77
import redis.asyncio as redis
8+
from mock import mock
89
from redis.asyncio.connection import Connection, to_bool
910
from redis.auth.token import TokenInterface
1011
from tests.conftest import skip_if_redis_enterprise, skip_if_server_version_lt
1112

12-
from .compat import aclosing, mock
13+
from .compat import aclosing
1314
from .test_pubsub import wait_for_message
1415

1516

tests/test_asyncio/test_pipeline.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import pytest
22
import redis
3+
from mock.mock import patch
34
from tests.conftest import skip_if_server_version_lt
45

5-
from .compat import aclosing, mock
6+
from .compat import aclosing
67
from .conftest import wait_for_command
78

89

@@ -295,7 +296,7 @@ async def mock_reset():
295296
nonlocal called
296297
called += 1
297298

298-
with mock.patch.object(pipe, "reset", mock_reset):
299+
with patch.object(pipe, "reset", mock_reset):
299300
await pipe.aclose()
300301
assert called == 1
301302

tests/test_asyncio/test_pubsub.py

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
import socket
44
import sys
55
from typing import Optional
6-
from unittest.mock import patch
6+
7+
from mock.mock import patch
78

89
# the functionality is available in 3.11.x but has a major issue before
910
# 3.11.3. See https://github.com/redis/redis-py/issues/2633
@@ -20,7 +21,7 @@
2021
from redis.utils import HIREDIS_AVAILABLE
2122
from tests.conftest import get_protocol_version, skip_if_server_version_lt
2223

23-
from .compat import aclosing, create_task, mock
24+
from .compat import aclosing
2425

2526

2627
def with_timeout(t):
@@ -733,7 +734,7 @@ async def loop_step():
733734
await messages.put(message)
734735
break
735736

736-
task = asyncio.get_running_loop().create_task(loop())
737+
task = asyncio.create_task(loop())
737738
# get the initial connect message
738739
async with async_timeout(1):
739740
message = await messages.get()
@@ -782,7 +783,7 @@ def callback(message):
782783
messages = asyncio.Queue()
783784
p = pubsub
784785
await self._subscribe(p, foo=callback)
785-
task = asyncio.get_running_loop().create_task(p.run())
786+
task = asyncio.create_task(p.run())
786787
await r.publish("foo", "bar")
787788
message = await messages.get()
788789
task.cancel()
@@ -805,8 +806,8 @@ def exception_handler_callback(e, pubsub) -> None:
805806
exceptions = asyncio.Queue()
806807
p = pubsub
807808
await self._subscribe(p, foo=lambda x: None)
808-
with mock.patch.object(p, "get_message", side_effect=Exception("error")):
809-
task = asyncio.get_running_loop().create_task(
809+
with patch.object(p, "get_message", side_effect=Exception("error")):
810+
task = asyncio.create_task(
810811
p.run(exception_handler=exception_handler_callback)
811812
)
812813
e = await exceptions.get()
@@ -823,7 +824,7 @@ def callback(message):
823824

824825
messages = asyncio.Queue()
825826
p = pubsub
826-
task = asyncio.get_running_loop().create_task(p.run())
827+
task = asyncio.create_task(p.run())
827828
# wait until loop gets settled. Add a subscription
828829
await asyncio.sleep(0.1)
829830
await p.subscribe(foo=callback)
@@ -867,7 +868,7 @@ async def mysetup(self, r, method):
867868
else:
868869
self.get_message = self.loop_step_listen
869870

870-
self.task = create_task(self.loop())
871+
self.task = asyncio.create_task(self.loop())
871872
# get the initial connect message
872873
message = await self.messages.get()
873874
assert message == {
@@ -903,7 +904,7 @@ async def test_reconnect_socket_error(self, r: redis.Redis, method):
903904
async with self.cond:
904905
assert self.state == 0
905906
self.state = 1
906-
with mock.patch.object(self.pubsub.connection, "_parser") as m:
907+
with patch.object(self.pubsub.connection, "_parser") as m:
907908
m.read_response.side_effect = socket.error
908909
m.can_read_destructive.side_effect = socket.error
909910
# wait until task noticies the disconnect until we

tests/test_asyncio/test_sentinel.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import socket
2-
from unittest import mock
32

43
import pytest
54
import pytest_asyncio
65
import redis.asyncio.sentinel
6+
from mock.mock import patch
77
from redis import exceptions
88
from redis.asyncio.sentinel import (
99
MasterNotFoundError,
@@ -259,7 +259,7 @@ async def mock_disconnect():
259259
nonlocal calls
260260
calls += 1
261261

262-
with mock.patch.object(pool, "disconnect", mock_disconnect):
262+
with patch.object(pool, "disconnect", mock_disconnect):
263263
await client.aclose()
264264

265265
assert calls == 1

0 commit comments

Comments
 (0)