【发布时间】:2021-01-14 23:43:19
【问题描述】:
所以我对嘲笑很陌生。我想我需要模拟两个函数。
被测函数
def get_text_from_pdf(next_pdfs_path):
# TODO test this function
"""
pulls all text from a PDF document and returns as a string.
Parameters:
next_pdfs_path (str): file path use r"" around path.
Returns:
text (str): string of text
"""
if os.path.isfile(next_pdfs_path): # check file is a real file/filepath
try:
text = ''
with fitz.open(next_pdfs_path) as doc: # using PyMuPDF
for page in doc:
text += page.getText()
return text
except (RuntimeError, IOError):
pass
pass
测试代码先试试
from unittest import mock
@mock.patch("content_production.fitz.open", return_value='fake_file.csv', autospec=True)
def test_get_text_from_pdf(mock_fitz_open):
assert cp.get_text_from_pdf('fake_file.csv') == 'fake_file.csv'
错误
E AssertionError: assert None == 'fake_file.csv'
E + where None = <function get_text_from_pdf at 0x00000245EDF8CAF0>('fake_file.csv')
E + where <function get_text_from_pdf at 0x00000245EDF8CAF0> = cp.get_text_from_pdf
我是否需要同时模拟 fitz.open 和 os.path.isfile?如果可以,怎么办?
编辑
根据 njriasan 的反馈,我已经尝试过了
@mock.patch("content_production.os.path.isfile", return_value=True, autospec=True)
@mock.patch("content_production.fitz.Page.getText")
@mock.patch("content_production.fitz.open")
def test_get_text_from_pdf(mock_fitz_open, mock_path_isfile, mock_gettext):
mock_fitz_open.return_value.__enter__.return_value = 'test'
assert cp.get_text_from_pdf('test') == 'test'
但现在出现此错误。
> text += page.getText()
E AttributeError: 'str' object has no attribute 'getText'
【问题讨论】:
标签: python-3.x unit-testing mocking pytest