在Pytest类函数中使用mock.patch+parametrize遇参数缺失错误的咨询
问题解决方法
你遇到的错误是因为在IsolatedAsyncioTestCase(unittest测试类)中混合使用pytest的@parametrize和unittest的@mock.patch时,参数传递顺序与装饰器顺序不匹配,导致pytest无法正确注入参数。保留parametrize的话,有两种可行方案:
方案一:调整装饰器与参数顺序(适配unittest测试类)
将@pytest.mark.parametrize放在@mock.patch的上方,同时把参数顺序改为self → parametrize参数 → mock参数。修改后的代码如下:
class TestGenerateAuthToken(IsolatedAsyncioTestCase): @pytest.mark.parametrize( "test_input,expected_result", [("user", "user_token"), ("admin", "admin_token")], ) @mock.patch("myaauth.get_token", new_callable=AsyncMock) async def test_get_auth_token(self, test_input, expected_result, get_token_mock): """Test get_auth_header""" def mock_generate_user_token(_type): return f"{_type}_token" get_token_mock.side_effect = mock_generate_user_token assert await myaauth.get_token(test_input) == expected_result
方案二:改用纯pytest异步测试(更推荐)
放弃unittest的IsolatedAsyncioTestCase,使用pytest原生的异步测试装饰器@pytest.mark.asyncio,这种方式兼容性更好,也更符合pytest的使用习惯:
方式1:上下文管理器式mock
import pytest from unittest.mock import AsyncMock, patch @pytest.mark.asyncio @pytest.mark.parametrize( "test_input,expected_result", [("user", "user_token"), ("admin", "admin_token")], ) async def test_get_auth_token(test_input, expected_result): """Test get_auth_header""" with patch("myaauth.get_token", new_callable=AsyncMock) as get_token_mock: def mock_generate_user_token(_type): return f"{_type}_token" get_token_mock.side_effect = mock_generate_user_token assert await myaauth.get_token(test_input) == expected_result
方式2:装饰器式mock
import pytest from unittest.mock import AsyncMock, patch @pytest.mark.asyncio @pytest.mark.parametrize( "test_input,expected_result", [("user", "user_token"), ("admin", "admin_token")], ) @patch("myaauth.get_token", new_callable=AsyncMock) async def test_get_auth_token(get_token_mock, test_input, expected_result): """Test get_auth_header""" def mock_generate_user_token(_type): return f"{_type}_token" get_token_mock.side_effect = mock_generate_user_token assert await myaauth.get_token(test_input) == expected_result
两种方案都能保留parametrize完成参数化测试,方案二更推荐,因为它避开了unittest与pytest的兼容性问题,测试代码也更简洁。
内容的提问来源于stack exchange,提问作者Carlos Rojas
相关产品推荐
相关产品推荐

