diff --git a/dev_requirements.txt b/dev_requirements.txt index 7ee7ac2b75..bf39dcdc92 100644 --- a/dev_requirements.txt +++ b/dev_requirements.txt @@ -5,7 +5,7 @@ flake8-isort flake8 flynt~=0.69.0 invoke==2.2.0 -mock +mock~=5.1.0 packaging>=20.4 pytest pytest-asyncio>=0.23.0,<0.24.0 diff --git a/tests/conftest.py b/tests/conftest.py index 8795c9f022..0f9b7a7d0d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -6,12 +6,11 @@ from datetime import datetime, timezone from enum import Enum from typing import Callable, TypeVar, Union -from unittest import mock -from unittest.mock import Mock from urllib.parse import urlparse import pytest import redis +from mock.mock import Mock, patch from packaging.version import Version from redis import Sentinel from redis.auth.idp import IdentityProviderInterface @@ -510,7 +509,7 @@ def _gen_cluster_mock_resp(r, response): connection = Mock(spec=Connection) connection.retry = Retry(NoBackoff(), 0) connection.read_response.return_value = response - with mock.patch.object(r, "connection", connection): + with patch.object(r, "connection", connection): yield r diff --git a/tests/test_asyncio/compat.py b/tests/test_asyncio/compat.py index aa1dc49af0..4a58b9ab09 100644 --- a/tests/test_asyncio/compat.py +++ b/tests/test_asyncio/compat.py @@ -1,11 +1,3 @@ -import asyncio -from unittest import mock - -try: - mock.AsyncMock -except AttributeError: - from unittest import mock - try: from contextlib import aclosing except ImportError: @@ -17,7 +9,3 @@ async def aclosing(thing): yield thing finally: await thing.aclose() - - -def create_task(coroutine): - return asyncio.create_task(coroutine) diff --git a/tests/test_asyncio/conftest.py b/tests/test_asyncio/conftest.py index 99ad155d0a..8a393e6e3b 100644 --- a/tests/test_asyncio/conftest.py +++ b/tests/test_asyncio/conftest.py @@ -1,6 +1,5 @@ import os import random -from contextlib import asynccontextmanager as _asynccontextmanager from datetime import datetime, timezone from enum import Enum from typing import Union @@ -8,7 +7,7 @@ import pytest import pytest_asyncio import redis.asyncio as redis -from mock.mock import Mock +from mock.mock import AsyncMock, Mock, patch from packaging.version import Version from redis.asyncio import Sentinel from redis.asyncio.client import Monitor @@ -37,8 +36,6 @@ ) from tests.conftest import REDIS_INFO -from .compat import mock - class AuthType(Enum): MANAGED_IDENTITY = "managed_identity" @@ -172,10 +169,10 @@ async def master(request, sentinel_setup): def _gen_cluster_mock_resp(r, response): - connection = mock.AsyncMock(spec=Connection) + connection = AsyncMock(spec=Connection) connection.retry = Retry(NoBackoff(), 0) connection.read_response.return_value = response - with mock.patch.object(r, "connection", connection): + with patch.object(r, "connection", connection): yield r @@ -403,32 +400,6 @@ async def wait_for_command( return None -# python 3.6 doesn't have the asynccontextmanager decorator. Provide it here. -class AsyncContextManager: - def __init__(self, async_generator): - self.gen = async_generator - - async def __aenter__(self): - try: - return await self.gen.__anext__() - except StopAsyncIteration as err: - raise RuntimeError("Pickles") from err - - async def __aexit__(self, exc_type, exc_inst, tb): - if exc_type: - await self.gen.athrow(exc_type, exc_inst, tb) - return True - try: - await self.gen.__anext__() - except StopAsyncIteration: - return - raise RuntimeError("More pickles") - - -def asynccontextmanager(func): - return _asynccontextmanager(func) - - # helpers to get the connection arguments for this run @pytest.fixture() def redis_url(request): diff --git a/tests/test_asyncio/test_cluster.py b/tests/test_asyncio/test_cluster.py index c95babf687..99a86fcbed 100644 --- a/tests/test_asyncio/test_cluster.py +++ b/tests/test_asyncio/test_cluster.py @@ -9,6 +9,7 @@ import pytest import pytest_asyncio from _pytest.fixtures import FixtureRequest +from mock import mock from redis._parsers import AsyncCommandsParser from redis.asyncio.cluster import ClusterNode, NodesManager, RedisCluster from redis.asyncio.connection import Connection, SSLConnection, async_timeout @@ -38,7 +39,7 @@ ) from ..ssl_utils import get_tls_certificates -from .compat import aclosing, mock +from .compat import aclosing pytestmark = pytest.mark.onlycluster diff --git a/tests/test_asyncio/test_connection.py b/tests/test_asyncio/test_connection.py index 38764d30cd..3869f4a6b2 100644 --- a/tests/test_asyncio/test_connection.py +++ b/tests/test_asyncio/test_connection.py @@ -2,10 +2,10 @@ import socket import types from errno import ECONNREFUSED -from unittest.mock import patch import pytest import redis +from mock import mock from redis._parsers import ( _AsyncHiredisParser, _AsyncRESP2Parser, @@ -25,7 +25,6 @@ from redis.utils import HIREDIS_AVAILABLE from tests.conftest import skip_if_server_version_lt -from .compat import mock from .mocks import MockStream @@ -43,7 +42,7 @@ async def test_invalid_response(create_redis): else: exp_err = f'Protocol error, got "{raw.decode()}" as reply type byte' - with mock.patch.object(parser, "_stream", fake_stream): + with mock.mock.patch.object(parser, "_stream", fake_stream): with pytest.raises(InvalidResponse, match=exp_err): await parser.read_response() @@ -86,8 +85,8 @@ async def get_conn(): init_call_count += 1 return mock_conn - with mock.patch.object(r.connection_pool, "get_connection", get_conn): - with mock.patch.object(r.connection_pool, "release"): + with mock.mock.patch.object(r.connection_pool, "get_connection", get_conn): + with mock.mock.patch.object(r.connection_pool, "release"): await asyncio.gather(r.set("a", "b"), r.set("c", "d")) assert init_call_count == 1 @@ -157,7 +156,7 @@ async def mock_connect(): async def test_connect_without_retry_on_os_error(): """Test that the _connect function is not being retried in case of a OSError""" - with patch.object(Connection, "_connect") as _connect: + with mock.patch.object(Connection, "_connect") as _connect: _connect.side_effect = OSError("") conn = Connection(retry_on_timeout=True, retry=Retry(NoBackoff(), 2)) with pytest.raises(ConnectionError): @@ -281,9 +280,9 @@ async def dummy_method(*args, **kwargs): pass # get dummy stream objects for the connection - with patch.object(asyncio, "open_connection", open_connection): + with mock.patch.object(asyncio, "open_connection", open_connection): # disable the initial version handshake - with patch.multiple( + with mock.patch.multiple( conn, send_command=dummy_method, read_response=dummy_method ): await conn.connect() @@ -325,7 +324,7 @@ async def mock_aclose(self): url: str = request.config.getoption("--redis-url") r1 = await Redis.from_url(url) - with patch.object(r1, "aclose", mock_aclose): + with mock.patch.object(r1, "aclose", mock_aclose): with pytest.deprecated_call(): await r1.close() assert calls == 1 @@ -382,7 +381,7 @@ async def mock_disconnect(_): nonlocal called called += 1 - with patch.object(ConnectionPool, "disconnect", mock_disconnect): + with mock.patch.object(ConnectionPool, "disconnect", mock_disconnect): async with await get_redis_connection() as r1: assert r1.auto_close_connection_pool is False @@ -414,7 +413,7 @@ async def mock_disconnect(_): nonlocal called called += 1 - with patch.object(ConnectionPool, "disconnect", mock_disconnect): + with mock.patch.object(ConnectionPool, "disconnect", mock_disconnect): async with await get_redis_connection() as r1: assert r1.auto_close_connection_pool is True @@ -441,7 +440,7 @@ async def mock_disconnect(_): nonlocal called called += 1 - with patch.object(ConnectionPool, "disconnect", mock_disconnect): + with mock.patch.object(ConnectionPool, "disconnect", mock_disconnect): async with await get_redis_connection() as r1: assert r1.auto_close_connection_pool is False @@ -461,7 +460,7 @@ async def test_client_garbage_collection(request): # create a client with a connection from the pool client = Redis(connection_pool=pool, single_connection_client=True) await client.initialize() - with mock.patch.object(client, "connection") as a: + with mock.mock.patch.object(client, "connection") as a: # we cannot, in unittests, or from asyncio, reliably trigger garbage collection # so we must just invoke the handler with pytest.warns(ResourceWarning): @@ -486,8 +485,8 @@ async def test_connection_garbage_collection(request): await client.initialize() conn = client.connection - with mock.patch.object(conn, "_reader"): - with mock.patch.object(conn, "_writer") as a: + with mock.mock.patch.object(conn, "_reader"): + with mock.mock.patch.object(conn, "_writer") as a: # we cannot, in unittests, or from asyncio, reliably trigger # garbage collection so we must just invoke the handler with pytest.warns(ResourceWarning): diff --git a/tests/test_asyncio/test_connection_pool.py b/tests/test_asyncio/test_connection_pool.py index 3d120e4ca7..7ce26b5492 100644 --- a/tests/test_asyncio/test_connection_pool.py +++ b/tests/test_asyncio/test_connection_pool.py @@ -1,15 +1,16 @@ import asyncio import re +from contextlib import asynccontextmanager import pytest import pytest_asyncio import redis.asyncio as redis +from mock import mock from redis.asyncio.connection import Connection, to_bool from redis.auth.token import TokenInterface from tests.conftest import skip_if_redis_enterprise, skip_if_server_version_lt -from .compat import aclosing, mock -from .conftest import asynccontextmanager +from .compat import aclosing from .test_pubsub import wait_for_message diff --git a/tests/test_asyncio/test_pipeline.py b/tests/test_asyncio/test_pipeline.py index 31759d84a3..7a7f7f3759 100644 --- a/tests/test_asyncio/test_pipeline.py +++ b/tests/test_asyncio/test_pipeline.py @@ -1,8 +1,9 @@ import pytest import redis +from mock.mock import patch from tests.conftest import skip_if_server_version_lt -from .compat import aclosing, mock +from .compat import aclosing from .conftest import wait_for_command @@ -295,7 +296,7 @@ async def mock_reset(): nonlocal called called += 1 - with mock.patch.object(pipe, "reset", mock_reset): + with patch.object(pipe, "reset", mock_reset): await pipe.aclose() assert called == 1 diff --git a/tests/test_asyncio/test_pubsub.py b/tests/test_asyncio/test_pubsub.py index 13a6158b40..0a8acbeef7 100644 --- a/tests/test_asyncio/test_pubsub.py +++ b/tests/test_asyncio/test_pubsub.py @@ -3,7 +3,8 @@ import socket import sys from typing import Optional -from unittest.mock import patch + +from mock.mock import patch # the functionality is available in 3.11.x but has a major issue before # 3.11.3. See https://github.com/redis/redis-py/issues/2633 @@ -20,7 +21,7 @@ from redis.utils import HIREDIS_AVAILABLE from tests.conftest import get_protocol_version, skip_if_server_version_lt -from .compat import aclosing, create_task, mock +from .compat import aclosing def with_timeout(t): @@ -733,7 +734,7 @@ async def loop_step(): await messages.put(message) break - task = asyncio.get_running_loop().create_task(loop()) + task = asyncio.create_task(loop()) # get the initial connect message async with async_timeout(1): message = await messages.get() @@ -782,7 +783,7 @@ def callback(message): messages = asyncio.Queue() p = pubsub await self._subscribe(p, foo=callback) - task = asyncio.get_running_loop().create_task(p.run()) + task = asyncio.create_task(p.run()) await r.publish("foo", "bar") message = await messages.get() task.cancel() @@ -805,8 +806,8 @@ def exception_handler_callback(e, pubsub) -> None: exceptions = asyncio.Queue() p = pubsub await self._subscribe(p, foo=lambda x: None) - with mock.patch.object(p, "get_message", side_effect=Exception("error")): - task = asyncio.get_running_loop().create_task( + with patch.object(p, "get_message", side_effect=Exception("error")): + task = asyncio.create_task( p.run(exception_handler=exception_handler_callback) ) e = await exceptions.get() @@ -823,7 +824,7 @@ def callback(message): messages = asyncio.Queue() p = pubsub - task = asyncio.get_running_loop().create_task(p.run()) + task = asyncio.create_task(p.run()) # wait until loop gets settled. Add a subscription await asyncio.sleep(0.1) await p.subscribe(foo=callback) @@ -867,7 +868,7 @@ async def mysetup(self, r, method): else: self.get_message = self.loop_step_listen - self.task = create_task(self.loop()) + self.task = asyncio.create_task(self.loop()) # get the initial connect message message = await self.messages.get() assert message == { @@ -903,7 +904,7 @@ async def test_reconnect_socket_error(self, r: redis.Redis, method): async with self.cond: assert self.state == 0 self.state = 1 - with mock.patch.object(self.pubsub.connection, "_parser") as m: + with patch.object(self.pubsub.connection, "_parser") as m: m.read_response.side_effect = socket.error m.can_read_destructive.side_effect = socket.error # wait until task noticies the disconnect until we @@ -989,9 +990,6 @@ async def loop_step_listen(self): @pytest.mark.onlynoncluster class TestBaseException: - @pytest.mark.skipif( - sys.version_info < (3, 8), reason="requires python 3.8 or higher" - ) async def test_outer_timeout(self, r: redis.Redis): """ Using asyncio_timeout manually outside the inner method timeouts works. @@ -1023,9 +1021,6 @@ async def get_msg_or_timeout(timeout=0.1): # the timeout on the read should not cause disconnect assert pubsub.connection.is_connected - @pytest.mark.skipif( - sys.version_info < (3, 8), reason="requires python 3.8 or higher" - ) async def test_base_exception(self, r: redis.Redis): """ Manually trigger a BaseException inside the parser's .read_response method diff --git a/tests/test_asyncio/test_sentinel.py b/tests/test_asyncio/test_sentinel.py index a27ba92bb8..fc67f41ca5 100644 --- a/tests/test_asyncio/test_sentinel.py +++ b/tests/test_asyncio/test_sentinel.py @@ -1,9 +1,9 @@ import socket -from unittest import mock import pytest import pytest_asyncio import redis.asyncio.sentinel +from mock.mock import patch from redis import exceptions from redis.asyncio.sentinel import ( MasterNotFoundError, @@ -259,7 +259,7 @@ async def mock_disconnect(): nonlocal calls calls += 1 - with mock.patch.object(pool, "disconnect", mock_disconnect): + with patch.object(pool, "disconnect", mock_disconnect): await client.aclose() assert calls == 1 diff --git a/tests/test_asyncio/test_sentinel_managed_connection.py b/tests/test_asyncio/test_sentinel_managed_connection.py index cae4b9581f..4147bb83d8 100644 --- a/tests/test_asyncio/test_sentinel_managed_connection.py +++ b/tests/test_asyncio/test_sentinel_managed_connection.py @@ -1,19 +1,18 @@ import socket import pytest +from mock.mock import AsyncMock from redis.asyncio.retry import Retry from redis.asyncio.sentinel import SentinelManagedConnection from redis.backoff import NoBackoff -from .compat import mock - pytestmark = pytest.mark.asyncio async def test_connect_retry_on_timeout_error(connect_args): """Test that the _connect function is retried in case of a timeout""" - connection_pool = mock.AsyncMock() - connection_pool.get_master_address = mock.AsyncMock( + connection_pool = AsyncMock() + connection_pool.get_master_address = AsyncMock( return_value=(connect_args["host"], connect_args["port"]) ) conn = SentinelManagedConnection( @@ -22,7 +21,7 @@ async def test_connect_retry_on_timeout_error(connect_args): connection_pool=connection_pool, ) origin_connect = conn._connect - conn._connect = mock.AsyncMock() + conn._connect = AsyncMock() async def mock_connect(): # connect only on the last retry diff --git a/tests/test_auth/test_token_manager.py b/tests/test_auth/test_token_manager.py index f675c125dd..2bd2f9b4a6 100644 --- a/tests/test_auth/test_token_manager.py +++ b/tests/test_auth/test_token_manager.py @@ -1,9 +1,9 @@ import asyncio from datetime import datetime, timezone from time import sleep -from unittest.mock import Mock import pytest +from mock.mock import Mock from redis.auth.err import RequestTokenErr, TokenRenewalErr from redis.auth.idp import IdentityProviderInterface from redis.auth.token import SimpleToken diff --git a/tests/test_cluster.py b/tests/test_cluster.py index 908ac26211..567808b1e9 100644 --- a/tests/test_cluster.py +++ b/tests/test_cluster.py @@ -7,10 +7,10 @@ import warnings from queue import LifoQueue, Queue from time import sleep -from unittest.mock import DEFAULT, Mock, call, patch import pytest import redis +from mock.mock import DEFAULT, Mock, call, patch from redis import Redis from redis._parsers import CommandsParser from redis.backoff import ExponentialBackoff, NoBackoff, default_backoff diff --git a/tests/test_commands.py b/tests/test_commands.py index f89c5f3365..07f689d258 100644 --- a/tests/test_commands.py +++ b/tests/test_commands.py @@ -5,11 +5,10 @@ import time from asyncio import CancelledError from string import ascii_letters -from unittest import mock -from unittest.mock import patch import pytest import redis +from mock.mock import MagicMock, patch from redis import exceptions from redis._parsers.helpers import ( _RedisCallbacks, @@ -5341,13 +5340,13 @@ def test_replicaof(self, r): assert r.replicaof("NO", "ONE") def test_shutdown(self, r: redis.Redis): - r.execute_command = mock.MagicMock() + r.execute_command = MagicMock() r.execute_command("SHUTDOWN", "NOSAVE") r.execute_command.assert_called_once_with("SHUTDOWN", "NOSAVE") @skip_if_server_version_lt("7.0.0") def test_shutdown_with_params(self, r: redis.Redis): - r.execute_command = mock.MagicMock() + r.execute_command = MagicMock() r.execute_command("SHUTDOWN", "SAVE", "NOW", "FORCE") r.execute_command.assert_called_once_with("SHUTDOWN", "SAVE", "NOW", "FORCE") r.execute_command("SHUTDOWN", "ABORT") diff --git a/tests/test_connection.py b/tests/test_connection.py index 6c1498a329..5eba2f9486 100644 --- a/tests/test_connection.py +++ b/tests/test_connection.py @@ -6,11 +6,10 @@ import types from errno import ECONNREFUSED from typing import Any -from unittest import mock -from unittest.mock import call, patch import pytest import redis +from mock.mock import Mock, call, patch from redis import ConnectionPool, Redis from redis._parsers import _HiredisParser, _RESP2Parser, _RESP3Parser from redis.backoff import NoBackoff @@ -44,7 +43,7 @@ def test_invalid_response(r): raw = b"x" parser = r.connection._parser - with mock.patch.object(parser._buffer, "readline", return_value=raw): + with patch.object(parser._buffer, "readline", return_value=raw): with pytest.raises(InvalidResponse, match=f"Protocol Error: {raw!r}"): parser.read_response() @@ -74,7 +73,7 @@ def inner(): class TestConnection: def test_disconnect(self): conn = Connection() - mock_sock = mock.Mock() + mock_sock = Mock() conn._sock = mock_sock conn.disconnect() mock_sock.shutdown.assert_called_once() @@ -84,7 +83,7 @@ def test_disconnect(self): def test_disconnect__shutdown_OSError(self): """An OSError on socket shutdown will still close the socket.""" conn = Connection() - mock_sock = mock.Mock() + mock_sock = Mock() conn._sock = mock_sock conn._sock.shutdown.side_effect = OSError conn.disconnect() @@ -95,7 +94,7 @@ def test_disconnect__shutdown_OSError(self): def test_disconnect__close_OSError(self): """An OSError on socket close will still clear out the socket.""" conn = Connection() - mock_sock = mock.Mock() + mock_sock = Mock() conn._sock = mock_sock conn._sock.close.side_effect = OSError conn.disconnect() @@ -110,7 +109,7 @@ def test_retry_connect_on_timeout_error(self): """Test that the _connect function is retried in case of a timeout""" conn = Connection(retry_on_timeout=True, retry=Retry(NoBackoff(), 3)) origin_connect = conn._connect - conn._connect = mock.Mock() + conn._connect = Mock() def mock_connect(): # connect only on the last retry @@ -138,7 +137,7 @@ def test_connect_timeout_error_without_retry(self): """Test that the _connect function is not being retried if retry_on_timeout is set to False""" conn = Connection(retry_on_timeout=False) - conn._connect = mock.Mock() + conn._connect = Mock() conn._connect.side_effect = socket.timeout with pytest.raises(TimeoutError, match="Timeout connecting to server"): diff --git a/tests/test_connection_pool.py b/tests/test_connection_pool.py index 65f42923fe..de507cc597 100644 --- a/tests/test_connection_pool.py +++ b/tests/test_connection_pool.py @@ -3,10 +3,10 @@ import time from contextlib import closing from threading import Thread -from unittest import mock import pytest import redis +from mock.mock import patch from redis.cache import CacheConfig from redis.connection import CacheProxyConnection, Connection, to_bool from redis.utils import HIREDIS_AVAILABLE, SSL_AVAILABLE @@ -691,7 +691,7 @@ def test_arbitrary_command_invokes_health_check(self, r): # invoke a command to make sure the connection is entirely setup r.get("foo") r.connection.next_health_check = time.time() - with mock.patch.object( + with patch.object( r.connection, "send_command", wraps=r.connection.send_command ) as m: r.get("foo") @@ -707,7 +707,7 @@ def test_arbitrary_command_advances_next_health_check(self, r): def test_health_check_not_invoked_within_interval(self, r): r.get("foo") - with mock.patch.object( + with patch.object( r.connection, "send_command", wraps=r.connection.send_command ) as m: r.get("foo") @@ -718,7 +718,7 @@ def test_health_check_in_pipeline(self, r): with r.pipeline(transaction=False) as pipe: pipe.connection = pipe.connection_pool.get_connection() pipe.connection.next_health_check = 0 - with mock.patch.object( + with patch.object( pipe.connection, "send_command", wraps=pipe.connection.send_command ) as m: responses = pipe.set("foo", "bar").get("foo").execute() @@ -729,7 +729,7 @@ def test_health_check_in_transaction(self, r): with r.pipeline(transaction=True) as pipe: pipe.connection = pipe.connection_pool.get_connection() pipe.connection.next_health_check = 0 - with mock.patch.object( + with patch.object( pipe.connection, "send_command", wraps=pipe.connection.send_command ) as m: responses = pipe.set("foo", "bar").get("foo").execute() @@ -741,7 +741,7 @@ def test_health_check_in_watched_pipeline(self, r): with r.pipeline(transaction=False) as pipe: pipe.connection = pipe.connection_pool.get_connection() pipe.connection.next_health_check = 0 - with mock.patch.object( + with patch.object( pipe.connection, "send_command", wraps=pipe.connection.send_command ) as m: pipe.watch("foo") @@ -765,7 +765,7 @@ def test_health_check_in_pubsub_before_subscribe(self, r): p = r.pubsub() p.connection = p.connection_pool.get_connection() p.connection.next_health_check = 0 - with mock.patch.object( + with patch.object( p.connection, "send_command", wraps=p.connection.send_command ) as m: assert not p.subscribed @@ -787,7 +787,7 @@ def test_health_check_in_pubsub_after_subscribed(self, r): p = r.pubsub() p.connection = p.connection_pool.get_connection() p.connection.next_health_check = 0 - with mock.patch.object( + with patch.object( p.connection, "send_command", wraps=p.connection.send_command ) as m: p.subscribe("foo") @@ -826,7 +826,7 @@ def test_health_check_in_pubsub_poll(self, r): """ p = r.pubsub() p.connection = p.connection_pool.get_connection() - with mock.patch.object( + with patch.object( p.connection, "send_command", wraps=p.connection.send_command ) as m: p.subscribe("foo") diff --git a/tests/test_graph.py b/tests/test_graph.py index efb10dada7..7bf0216271 100644 --- a/tests/test_graph.py +++ b/tests/test_graph.py @@ -1,6 +1,5 @@ -from unittest.mock import patch - import pytest +from mock.mock import patch from redis import Redis from redis.commands.graph import Edge, Node, Path from redis.commands.graph.execution_plan import Operation diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index be7784ad0b..77164908cb 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -1,8 +1,8 @@ from contextlib import closing -from unittest import mock import pytest import redis +from mock.mock import patch from .conftest import skip_if_server_version_lt, wait_for_command @@ -296,7 +296,7 @@ def mock_reset(): nonlocal called called += 1 - with mock.patch.object(pipe, "reset", mock_reset): + with patch.object(pipe, "reset", mock_reset): pipe.close() assert called == 1 diff --git a/tests/test_pubsub.py b/tests/test_pubsub.py index fb46772af3..adabd9f882 100644 --- a/tests/test_pubsub.py +++ b/tests/test_pubsub.py @@ -4,11 +4,10 @@ import threading import time from collections import defaultdict -from unittest import mock -from unittest.mock import patch import pytest import redis +from mock.mock import patch from redis.exceptions import ConnectionError from redis.utils import HIREDIS_AVAILABLE @@ -964,7 +963,7 @@ def exception_handler(ex, pubsub, thread): p = r.pubsub() p.subscribe(**{"foo": lambda m: m}) - with mock.patch.object(p, "get_message", side_effect=Exception("error")): + with patch.object(p, "get_message", side_effect=Exception("error")): pubsub_thread = p.run_in_thread( daemon=True, exception_handler=exception_handler ) @@ -1041,7 +1040,7 @@ def test_reconnect_socket_error(self, r: redis.Redis, method): # now, disconnect the connection, and wait for it to be re-established with self.cond: self.state = 1 - with mock.patch.object(self.pubsub.connection, "_parser") as mockobj: + with patch.object(self.pubsub.connection, "_parser") as mockobj: mockobj.read_response.side_effect = socket.error mockobj.can_read.side_effect = socket.error # wait until thread notices the disconnect until we undo the patch diff --git a/tests/test_retry.py b/tests/test_retry.py index e1e4c414a4..220f39fad2 100644 --- a/tests/test_retry.py +++ b/tests/test_retry.py @@ -1,6 +1,5 @@ -from unittest.mock import patch - import pytest +from mock.mock import patch from redis.backoff import AbstractBackoff, ExponentialBackoff, NoBackoff from redis.client import Redis from redis.connection import Connection, UnixDomainSocketConnection diff --git a/tests/test_sentinel.py b/tests/test_sentinel.py index 93455f3290..d44f44ecec 100644 --- a/tests/test_sentinel.py +++ b/tests/test_sentinel.py @@ -1,8 +1,8 @@ import socket -from unittest import mock import pytest import redis.sentinel +from mock.mock import patch from redis import exceptions from redis.sentinel import ( MasterNotFoundError, @@ -261,7 +261,7 @@ def mock_disconnect(): nonlocal calls calls += 1 - with mock.patch.object(pool, "disconnect", mock_disconnect): + with patch.object(pool, "disconnect", mock_disconnect): client.close() assert calls == 1