[英]pytest - using patch as a decorator to patch a constant
I have an object MyObject
which uses a constant defined in mymodule.constants.MYCONSTANT
.我有一个对象
MyObject
,它使用在mymodule.constants.MYCONSTANT
定义的常量。 I can successfully patch the constant using a context manger like so:我可以使用上下文管理器成功修补常量,如下所示:
import pytest
from unittest.mock import patch
def test_constant(self):
with patch('mymodule.constants.MYCONSTANT', 3):
MyObject()
However, I can't figure out how to use the equivalent patching using patch
as a decorator:但是,我无法弄清楚如何使用
patch
作为装饰器来使用等效的补丁:
@patch('mymodule.constants.MYCONSTANT', 3)
def test_constant(self, mock_constant):
MyObject()
The above fails with a fixture mock_constant not found
error.上面的代码失败了,出现了一个
fixture mock_constant not found
错误。 I tried using我尝试使用
@patch('mymodule.constants.MYCONSTANT', return_value=3)
But MYCONSTANT
doesn't get replaced with the value of 3.但是
MYCONSTANT
不会被替换为 3 的值。
This is aligned to the behavior as documented :这对准行为记录:
unittest.mock.patch(target, new=DEFAULT, spec=None, create=False, spec_set=None, autospec=None, new_callable=None, **kwargs)
... If
patch()
is used as a decorator and new is omitted, the created mock is passed in as an extra argument to the decorated function.... 如果
patch()
用作装饰器并且省略 new ,则创建的模拟将作为额外参数传递给装饰函数。
So, if you want to pass the extra argument to the decorated function, don't set the new
argument:因此,如果要将额外参数传递给装饰函数,请不要设置
new
参数:
@patch('mymodule.constants.MYCONSTANT')
def test_constant(self, mock_constant):
...
Setting the new
argument means no extra argument would be passed:设置
new
参数意味着不会传递额外的参数:
@patch('mymodule.constants.MYCONSTANT', 3)
def test_constant(self):
...
Guys the order of parameters matter so first mocks then fixtures , otherwise it will still throw you the same error.伙计们,参数的顺序很重要,所以首先模拟然后装置,否则它仍然会给你带来同样的错误。
@patch('server.app.UserValidator')
def test_first_mocks(self,mock_user_validator:MagicMock,client_fixture:FlaskClient):
# Arrange
input = {'password':'internal','username':'error'}
mock_user_validator.side_effect = ValueError('testing')
# Act
response = client_fixture.post('/api/users',json=input)
# Assert
mock_user_validator.assert_called_once()
assert response.status_code == 500
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.