用于检查文件路径的带mock的python单元测试

2024-05-15 12:34:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我在'au.py'中有以下python函数:

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_PATHRES_PATH的存在,以便验证函数。在将来,这个单元测试应该能够模拟删除一些文件,然后再编写我正在测试这个简单的文件


Tags: pathimportreturnisosconfetcres
2条回答

Mocks根据定义是一种模拟对象的方法。您正在尝试处理函数中的变量(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"

谢谢@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" 

相关问题 更多 >