因此,由于上下文管理器,我正在努力模拟此功能。
被测功能
import fitz
def with_test_func(next_pdfs_path):
text = ''
with fitz.open(next_pdfs_path) as doc:
text = doc
return text
测试码
@mock.patch("content_production.fitz.open.__enter__", return_value='value_out')
def test_with_test_func(mock_fitz_open):
assert cp.with_test_func('value_in') == 'value_out'
错误
RuntimeError: cannot open value_in: No such file or directory
我已经在没有上下文管理器的情况下对其进行了测试,并且可以正常工作。那么我该如何解决呢?谢谢
编辑
因此,按照@MrBean的建议,我尝试了
@mock.patch("content_production.fitz.open.return_value.__enter__", return_value='value_out')
def test_with_test_func(mock_fitz_open):
assert cp.with_test_func('value_in') == 'value_out'
它给我这个错误
thing = <class 'fitz.fitz.Document'>, comp = 'return_value', import_path = 'content_production.fitz.open.return_value'
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
> __import__(import_path)
E ModuleNotFoundError: No module named 'content_production.fitz'; 'content_production' is not a package
问题在于这return_value
是模拟的属性,而不是修补的函数的属性,因此您不能将其放入patch
参数字符串中。相反,您必须在open
方法的模拟上设置返回值:
@mock.patch("content_production.fitz.open")
def test_with_test_func(mock_fitz_open):
mock_fitz_open.return_value.__enter__.return_value = 'value_out'
assert cp.with_test_func('value_in') == 'value_out'
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句