I would like to know how to write Python 3 unittest for try except
blocks
that are defined outside of function definitions in Python's module.
Imagine that in package/module.py
I have a block of code like:
import os
try:
CONSTANT = os.environ['NOT_EXISTING_KEY']
except KeyError:
CONSTANT = False
finally:
del os
(please don't mind the actual code, I know I could have used os.getenv('NOT_EXISTING_KEY', False)
in this specific case, what I am interested in is really testing that the try-except block in a module (outside of a function) behaves as expected.
How can I write a unit test that checks that package.module.CONSTANT
is set to the expected value?
In the unittest file (I use pytest) I have something like:
from package.module import CONSTANT
def test_constant_true():
assert CONSTANT == 'expected_value'
to test that if the try block executed correctly then CONSTANT is as expected.
I don't know, however, how to mock the import machinery so that the os.environ in the try block raises an exception and I can test that CONSTANT is set to False.
How can I do that?