如何解决重用补丁语句
在很多单元测试中我都重复了这两个语句。
with patch('/path') as mocked_thing1:
mocked_thing1.return_value = 'some value'
with patch('/path') as mocked_thing2:
mocked_thing2.return_value = 'some value'
有没有办法为它编写一个函数,然后调用它,而不是在测试用例中重复编写这些行?
解决方法
如果要更改不同测试的返回值,则只能在每个测试中分配返回值。一种方法是为模拟添加单独的装置:
@pytest.fixture
def mock_thing1():
with patch('/path') as mocked_thing1:
yield mocked_thing1
@pytest.fixture
def mock_thing2():
with patch('/path') as mocked_thing2:
yield mocked_thing2
def test_something(mock_thing1,mock_thing2):
mocked_thing1.return_value = 'some value'
mocked_thing2.return_value = 'some value'
...
另一种可能性是使用间接夹具参数来设置夹具中的返回值:
@pytest.fixture
def mock_thing1(request):
with patch('/path') as mocked_thing1:
mocked_thing1.return_value = request.param
yield mocked_thing1
@pytest.fixture
def mock_thing2(request):
with patch('/path') as mocked_thing2:
mocked_thing2.return_value = request.param
yield mocked_thing2
@pytest.mark.parametrize("mock_thing2",['some other value'],indirect=True)
@pytest.mark.parametrize("mock_thing1",['some value'],indirect=True)
def test_something(mock_thing1,mock_thing2):
...
或者您可以只使用patch
的装饰器版本而不是任何灯具,这样至少可以更好地读取测试体:
@mock.patch("mock_thing2",return_value='some other value')
@mock.patch("mock_thing1",return_value='some value')
def test_something(mock_thing1,mock_thing2):
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。