0

I have some code like:

if not settings.VAR_URL: 
    raise Exception("VAR_URL is not defined") 

When I try to test it like:

def test_for_absent_env(self):
    del os.environ['VAR_URL']
    o = Object()
    with self.assertRaises(Exception) as error:
        o.some_function()

        self.assertEqual(error.exception.message, "VAR_URL is not defined")

But it gives KeyError instead of passed test. What should I correct?

1 Answers1

1

That's not the way you should be testing if an exception is raised. There is a specific assertion called assertRaises, which can be used as a context manager (helps to then get the error message to check as well):

with self.assertRaises(Exception) as error: 
    o.some_cool_function()

    self.assertEqual(error.exception.message, "VAR_URL is not defined")

Note that the ability to use assertRaises as a context manager is available in Python>=3.1.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Thank you! I changed test according to your advice, but still have same mistake – Ekaterina Premudraya Jan 05 '18 at 18:36
  • @EkaterinaPremudraya voobshe ne vopros :) On what line does the error happen? Could you edit the question and also post the traceback? Thanks. – alecxe Jan 05 '18 at 18:39
  • spasibo po svoiski))))) it happens on del os.environ['ENV_URL'] line. It gives raise KeyError(key) from None – Ekaterina Premudraya Jan 05 '18 at 18:48
  • @EkaterinaPremudraya ah, that means that you don't have the `ENV_URL` key in the `os.environ` dictionary. In other words, the environment variable is not set. By the way, are you sure you need to work with environment variables here at all? In your code that you've shown, you only have the `if not settings.VAR_URL`..could it be that you should "patch" this `settings` object instead? Is it a Django project? Thanks. – alecxe Jan 05 '18 at 18:50
  • I wish it could be Django, but it is python script. The if statement is for case where user don't activate or don't have envs. So to imitate situation of absent envs I delete it – Ekaterina Premudraya Jan 05 '18 at 18:55
  • @EkaterinaPremudraya okay, by the looks of it, you just don't need to delete anything in this test and the environment variable was just not set. – alecxe Jan 05 '18 at 18:58