我正在尝试使用pytest fixture来模拟对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()
函数,也会发生这种情况。但是如果我把模拟代码放在测试函数本身(我显然不想这样做),那么它可以正常工作。
我错过了什么?谢谢!
答案 0 :(得分:13)
如何使用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