Rajesh P S
Rajesh P S

Reputation: 21

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

Upvotes: 0

Views: 3717

Answers (2)

Rajesh P S
Rajesh P S

Reputation: 21

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" 

Upvotes: 1

Mauro Baraldi
Mauro Baraldi

Reputation: 6550

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"

Upvotes: 1

Related Questions