我有一个函数调用一个子函数来打开一个文件。我试图测试父函数,但我想修补子函数并让它返回我传入的数据(就像它是从文件中读取的一样)。
测试.py
# Read in the sample data
__SAMPLE_LOG = os.path.join(settings.BASE_DIR, "apps/tests/log_viewer/sample_logs/sample_manager_log.log")
sample_data = []
for line in reversed_lines(open(__SAMPLE_LOG)):
sample_data.append(line)
sample_data = ('').join(sample_data)
class ReadLog(TestCase):
@patch('apps.log_viewer.utils.reversed_lines', new_callable = mock_open, read_data = sample_data)
def test_returnsDictionaryContainingListOfDictionaries(self, mock_file):
activity = read_log()
# Make sure the sample data was read ==> this fails.
self.assertEqual(open(settings.ACTIVITY_LOG_FILE).read(), sample_data)
实用程序.py
def read_log():
# This is the line I am trying to patch
for line in reversed_lines(open(settings.ACTIVITY_LOG_FILE)):
# process data
# see: https://stackoverflow.com/questions/260273/most-efficient-way-to-search-the-last-x-lines-of-a-file-in-python/260433#260433
def reversed_lines(file):
"Generate the lines of file in reverse order."
part = ''
for block in reversed_blocks(file):
for c in reversed(block):
if c == '\n' and part:
yield part[::-1]
part = ''
part += c
if part: yield part[::-1]
def reversed_blocks(file, blocksize=4096):
"Generate blocks of file's contents in reverse order."
file.seek(0, os.SEEK_END)
here = file.tell()
while 0 < here:
delta = min(blocksize, here)
here -= delta
file.seek(here, os.SEEK_SET)
yield file.read(delta)
错误
我试图在
reversed_lines()
方法中修补utils.py
中的read_log()
,但read_log()
仍在读取实际日志,这表明我没有正确修补reversed_lines()
。当我改变
@patch('apps.log_viewer.utils.reversed_lines', new_callable = mock_open, read_data = sample_data)
到
@patch('builtins.open', new_callable = mock_open, read_data = sample_data)
我明白了
======================================================================
ERROR: test_returnsDictionaryContainingListOfDictionaries
(tests.log_viewer.test_utils.ReadLog)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/unittest/mock.py", line 1209, in patched
return func(*args, **keywargs)
File "/webapp/apps/tests/log_viewer/test_utils.py", line 32, in test_returnsDictionaryContainingListOfDictionaries
activity = read_log()
File "/webapp/apps/log_viewer/utils.py", line 64, in read_log
for line in reversed_lines(open(settings.ACTIVITY_LOG_FILE)):
File "/webapp/apps/log_viewer/utils.py", line 173, in reversed_lines
for block in reversed_blocks(file):
File "/webapp/apps/log_viewer/utils.py", line 164, in reversed_blocks
while 0 < here:
TypeError: '<' not supported between instances of 'int' and 'MagicMock'
我哪里做错了?
最佳答案
按照https://docs.python.org/3.3/library/unittest.mock.html#mock-open文档中的示例,我想您需要
@patch('builtins.open', mock_open(read_data = sample_data), create=True)
然而,通过
mock_open
:https://github.com/python/cpython/blob/3.7/Lib/unittest/mock.py#L2350的来源阅读似乎filehandles的
tell
方法不是由mock实现的。唯一支持的方法是read
、readline
、readlines
、write
和对内容进行迭代。您需要手动设置tell
方法的模拟。这不是一般的实现,但适用于您的具体情况:class ReadLog(TestCase):
@patch('builtins.open', mock_open(read_data = sample_data), create=True)
def test_returnsDictionaryContainingListOfDictionaries(self, mock_file):
mock_file.return_value.tell.return_value = len(sample_data)
...
关于python - 使用mock_open修补功能在哪里出错?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57515970/