简体   繁体   中英

python unit test with mock for checking file path

I have following python function in 'au.py' :

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"

I need to write a unit test with mock which can check the path exists or not following is the unit test which I wrote

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"

but I am getting following error

AttributeError: <function isfile at 0x10bdea6a8> does not have the attribute 'ALT_PATH'

How do I mock to check the presence of ALT_PATH and RES_PATH so that I can validate the function. In future this unit test should have the capability to mock removal some files, before writing that I am testing this simple one

Thanks @ Mauro Baraldi, as per your suggestion, I changed the code little bit and it works fine now

    def test_both_source_files_not(self, mock_os_is_file):
        mock_os_is_file.side_effect = [False , False]
        assert resolv_conf_audit() == "FAILED" 

Mocks by definition is a way to simulate beahvior of objects. You are trying to handle a variable ( ALT_PATH ) inside your function.

All you need is to mock just the os.path.isfile method.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM