【发布时间】:2018-03-20 07:24:45
【问题描述】:
我有一个类,其方法使用 shutil.rmtree 如果参数被传递为 true 来删除一些文件,如何模拟这种行为,以便其他需要这些文件的测试不会中断。
我的班级看起来像这样 -
class FileConverter(object):
def __init__(self, path_to_files):
self._path_to_files = path_to_files
def convert_files(self, rmv_src=False):
doStuff()
if rmv_src:
shutil.rmtree(self.__path_to_files)
def doStuff():
# does some stuff
现在我的测试看起来像 -
class TestFileConverter(unittest.TestCase):
def test_convert_success(self):
input_dir = 'resources/files'
file_converter = FileConverter(input_dir)
file_converter.convert_files()
# assert the things from doStuff
@mock.patch('shutil.rmtree')
def test_convert_with_rmv(self, rm_mock):
input_dir = 'resources/files'
file_converter = FileConverter(input_dir)
file_converter.convert_files(True)
self.assertEquals(rm_mock, [call(input_dir)])
现在当我运行这个测试套件时,使用 rmv 的测试给了我 assertionError
<MagicMock name='rmtree' id='139676276822984'> != [call('resources/images')]
第一个测试给了我文件未找到错误,因为模拟不起作用并且 rmv 源测试删除了文件
FileNotFoundError: [Errno 2] No such file or directory: 'resources/images'
如果我用 rmv_source true 注释掉第二个测试,那么我的第一个测试工作正常。 我在这里做错了什么?
【问题讨论】:
标签: python unit-testing testing mocking