我正在尝试使用pytest固定装置模拟对调用的调用open()
,然后在测试拆解时将其重置,但是由于某种原因,该模拟未应用到测试函数中。
这是我所拥有的样本:
# tests.py
@pytest.fixture(scope='module')
def mock_open(request):
mock = flexmock(sys.modules['__builtin__'])
mock.should_call('open')
m = (mock.should_receive('open')
.with_args('/tmp/somefile')
.and_return(read=lambda: 'file contents'))
request.addfinalizer(lambda: m.reset())
def test_something(mock_open):
ret = function_to_test()
ret[1]() # This actually uses the original open()
并且,如果有问题的话,function_to_test()
如下所示:
# some_module.py
def function_to_test():
def inner_func():
open('/tmp/somefile').read() # <-- I want this call mocked
# More code ...
return (True, inner_func)
如果我使用xUnit样式setup_module()
/teardown_module()
功能,也会发生这种情况。但是,如果我将模拟代码放在测试函数本身中(我显然不想这样做),那么它可以正常工作。
我想念什么?谢谢!
怎么样使用mock
?
tests.py:
import mock # import unittest.mock (Python 3.3+)
import pytest
from some_module import function_to_test
@pytest.fixture(scope='function')
def mock_open(request):
m = mock.patch('__builtin__.open', mock.mock_open(read_data='file content'))
m.start()
request.addfinalizer(m.stop)
def test_something(mock_open):
ret = function_to_test()
assert ret[1]() == 'file content'
some_module.py:
def function_to_test():
def inner_func():
return open('/tmp/somefile').read()
return True, inner_func
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句