[英]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.