【发布时间】:2022-01-26 09:39:54
【问题描述】:
我有一个生产功能,可以读取一个文件,并且在某些情况下还写入(不止一次)另一个文件(带有详细的错误输出)。
我能够模拟文件读取并在单元测试中给出特定的文件内容。但我不知道如何测试写入第二个文件的内容,该文件也通过mock_open() 模拟。
重要的一点是,我对在单元测试时将真实文件写入文件系统不感兴趣。
这是生产代码:
import pathlib
def my_prod_code(fp):
with fp.open('r') as if:
result = if.read()
with fp.with_suffix('.error.out').open('w') as of:
of.write(f'Read {result}.')
of.write('FIN.')
return result
那是单元测试
import unittest
from unittest import mock
import pathlib
class MyTest(unittest.TestCase):
def test_foobar(self, mock_unlink):
opener = mock.mock_open(read_data='foobar')
with mock.patch('pathlib.Path.open', opener):
result = my_prod_code(pathlib.Path('file.in'))
self.assertEqual(result, 'foobar')
# Want to check for the written content also
【问题讨论】:
标签: python unit-testing mocking