[英]python unit test with mock for checking file path
我在'au.py'
中有以下 python function :
import os
def resolv_conf_audit():
ALT_PATH = "/etc/monitor/etc/resolv.conf.{}".format(os.uname()[1])
RES_PATH = "/data/bin/resolvconf"
if os.path.isfile(RES_PATH):
return "PASSED", "/data/bin/resolvconf is present"
elif os.path.isfile(ALT_PATH):
return "PASSED", "/etc/monitor/etc/resolv.conf. is present"
else:
return "FAILED"
我需要用 mock 编写一个单元测试,它可以检查路径是否存在 以下是我编写的单元测试
from au import resolv_conf_audit
import unittest
from unittest.mock import patch
class TestResolvConf(unittest.TestCase):
@patch('os.path.isfile.ALT_PATH')
def test_both_source_files_not(self, mock_os_is_file):
mock_os_is_file.return_value = False
assert resolv_conf_audit() == "FAILED"
但我收到以下错误
AttributeError: <function isfile at 0x10bdea6a8> does not have the attribute 'ALT_PATH'
如何模拟检查ALT_PATH
和RES_PATH
的存在,以便我可以验证 function。 将来这个单元测试应该能够模拟删除一些文件,然后再写我正在测试这个简单的
谢谢@Mauro Baraldi,根据您的建议,我稍微更改了代码,现在可以正常工作
def test_both_source_files_not(self, mock_os_is_file):
mock_os_is_file.side_effect = [False , False]
assert resolv_conf_audit() == "FAILED"
根据定义,模拟是一种模拟对象行为的方法。 您正在尝试处理 function 中的变量 ( ALT_PATH
)。
您所需要的只是模拟os.path.isfile方法。
class TestResolvConf(unittest.TestCase):
@patch('os.path.isfile')
def test_both_source_files_not(self, mock_os_is_file):
mock_os_is_file.return_value = False
assert resolv_conf_audit() == "FAILED"
@patch('os.path.isfile')
def test_both_source_files_exists(self, mock_os_is_file):
mock_os_is_file.return_value = True
assert resolv_conf_audit() == "PASSED"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.