Unit testing for "FileNotFoundError" in python

I have the following code and want a utility when the given function is raised for "FileNotFoundError

def get_token():
try:
    auth = get_auth() # This function returns auth ,if file exists else throws "FileNotFoundError
except FileNotFoundError: 
    auth= create_auth()
return auth

      

I'm having trouble figuring out how to check for a condition where it raises a "FileNotFoundError" and doesn't call create_auth.

Any hint would be appreciated

thank

+3


source to share


1 answer


In your unit test, you will need to mock the function get_auth

and force it to raise FileNotFoundError

with an attribute .side_effect

:

@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth):
    mock_get_auth.side_effect = FileNotFoundError

      



Then you can check if it was actually called create_auth

:

@mock.patch('path.to.my.file.create_auth')
@mock.patch('path.to.my.file.get_auth')
def test_my_test(self, mock_get_auth, mock_create_auth):
    mock_get_auth.side_effect = FileNotFoundError
    get_token()
    self.assertTrue(mock_create_auth.called)

      

+4


source







All Articles