我有一个函数,它调用一个子函数来打开一个文件。我试图测试父函数,但我想修补子函数并让它返回我传入的数据(就像它从文件中读取一样)。在
测试.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'
我哪里出错了?在
按照https://docs.python.org/3.3/library/unittest.mock.html#mock-open文档中的示例,我想您需要
但是通过
mock_open
的源代码阅读:https://github.com/python/cpython/blob/3.7/Lib/unittest/mock.py#L2350mock似乎没有实现filehandles的
^{pr2}$tell
方法。唯一支持的方法是read
、readline
、readlines
、write
以及对内容进行迭代。您需要为tell
方法手动设置模拟。这不是一个一般的实现,但将在您的特定情况下起作用:相关问题 更多 >
编程相关推荐