如何用 pathlib.Path 对象模拟文件大小?
how to mock file size with pathlib.Path objects?
在我的函数中,我之前使用 os.path.getsize
函数来获取文件大小。
所以在我的测试服中,我使用以下内容来测试我的函数的结果值:
# init test values
test_value = 7.5
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
# mock 0 B file
with patch('os.path.getsize', return_value=0):
txt = su.get_file_size('random')
self.assertEqual(txt, '0B')
# mock every pow of 1024 to YB
for i in range(9):
with patch('os.path.getsize', return_value=test_value*(1024**i)):
txt = su.get_file_size('random')
self.assertEqual(txt, f'7.5 {size_name[i]}')
现在我在内部使用 pathlib.Path
对象作为文件。所以我现在想模拟 Path(filename).stat().st_size
。谁能告诉我应该在 with 语句中使用什么而不是补丁?
如果您在测试模块中使用 from pathlib import Path
导入 Path
,您可以使用类似这样的东西(查看 where to patch 了解更多信息):
with patch('yourmodule.su.Path.stat') as stat:
stat.return_value.st_size = 0
txt = get_file_size('random')
由于方法调用 (stat()
),您不能直接模拟整个表达式,您必须使用 return_value
模拟它,但它应该足够简单。
在我的函数中,我之前使用 os.path.getsize
函数来获取文件大小。
所以在我的测试服中,我使用以下内容来测试我的函数的结果值:
# init test values
test_value = 7.5
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
# mock 0 B file
with patch('os.path.getsize', return_value=0):
txt = su.get_file_size('random')
self.assertEqual(txt, '0B')
# mock every pow of 1024 to YB
for i in range(9):
with patch('os.path.getsize', return_value=test_value*(1024**i)):
txt = su.get_file_size('random')
self.assertEqual(txt, f'7.5 {size_name[i]}')
现在我在内部使用 pathlib.Path
对象作为文件。所以我现在想模拟 Path(filename).stat().st_size
。谁能告诉我应该在 with 语句中使用什么而不是补丁?
如果您在测试模块中使用 from pathlib import Path
导入 Path
,您可以使用类似这样的东西(查看 where to patch 了解更多信息):
with patch('yourmodule.su.Path.stat') as stat:
stat.return_value.st_size = 0
txt = get_file_size('random')
由于方法调用 (stat()
),您不能直接模拟整个表达式,您必须使用 return_value
模拟它,但它应该足够简单。