在mock峎打开的情况下修补函数会出什么问题?

2024-03-29 10:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它调用一个子函数来打开一个文件。我试图测试父函数,但我想修补子函数并让它返回我传入的数据(就像它从文件中读取一样)。在

测试.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

^{2}$

错误

我试图在read_log()方法内的utils.py中修补reversed_lines(),但{}仍在从实际日志中读取,这表明我没有正确地修补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'

我哪里出错了?在


Tags: appssampleinpytestlogreaddata
1条回答
网友
1楼 · 发布于 2024-03-29 10:46:32

按照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

mock似乎没有实现filehandles的tell方法。唯一支持的方法是readreadlinereadlineswrite以及对内容进行迭代。您需要为tell方法手动设置模拟。这不是一个一般的实现,但将在您的特定情况下起作用:

^{pr2}$

相关问题 更多 >