0

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

2 Answers 2

1

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"
Sign up to request clarification or add additional context in comments.

2 Comments

Newbie question, Where does mock_os_is_file come from or gets created? Is it a default thing created by @patch('os.path.isfile')?
This is the name you can give to mock object. I could be banana, but it may not make sense for the context :-P
1

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" 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.