使用 mock 测试目录是否存在 [英] Using mock to test if directory exists or not
问题描述
这几天我一直在探索 mock 和 pytest.
I have been exploring mock and pytest for a few days now.
我有以下方法:
def func():
if not os.path.isdir('/tmp/folder'):
os.makedirs('/tmp/folder')
为了进行单元测试,我决定打补丁os.path.isdir和os.makedirs,如图:
In order to unit test it, I have decided to patch os.path.isdir and os.makedirs, as shown:
@patch('os.path.isdir')
@patch('os.makedirs')
def test_func(patch_makedirs, patch_isdir):
patch_isdir.return_value = False
assert patch_makedirs.called == True
断言失败,与 patch_isdir 的返回值无关.有人可以帮我弄清楚我哪里出错了吗?
The assertion fails, irrespective of the return value from patch_isdir. Can someone please help me figure out where I am going wrong?
推荐答案
不能肯定有完整的代码,但我感觉它与 你打补丁的地方.
Can't say for sure having the complete code, but I have the feeling it's related to where you're patching.
您应该修补由被测模块导入的 os
模块.
You should patch the os
module that was imported by the module under test.
所以,如果你有这样的:
So, if you have it like this:
mymodule.py:
def func():
if not os.path.isdir('/tmp/folder'):
os.makedirs('/tmp/folder')
你应该像这样制作你的_test_mymodule.py_:
you should make your _test_mymodule.py_ like this:
@patch('mymodule.os')
def test_func(self, os_mock):
os_mock.path.isdir.return_value = False
assert os_mock.makedirs.called
请注意,这个特定的测试并没有那么有用,因为它本质上是在测试模块 os
是否有效——您可以假设它已经过良好的测试.;)
Note that this specific test is not that useful, since it's essentially testing if the module os
works -- and you can probably assume that is well tested. ;)
如果专注于您的应用程序逻辑(也许是调用 func
的代码?),您的测试可能会更好.
Your tests would probably be better if focused on your application logic (maybe, the code that calls func
?).
这篇关于使用 mock 测试目录是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!