I have a source file util.py and there I have below one, where day is an AWS lambda environment variable.
import os
day = os.getenv("DAY")
def get_day_code():
if day == "Monday":
return "M"
if day == "Tuesday":
return "T"
if day == "Wednesday":
return "W"
I need to write a unit test for this function. I tried using pytest paramaterise, but nothing works. Any help would be really appreciated.
Since
os.getenvreturnsNone, if no environment variable with the provided name is found, you don't need to mock that function. Instead, you can simply patch the global variabledayduring your tests.unittest.mock.patchcan be used in the form of a context manager. That way you can easily probe every branch of your function in a loop.Assuming your code resides in a module named
util, here is a working example test module:If you want to use
pytest, you can also inject temporary environment variables usingmonkeypatch.setenv, but I would argue that there again directly patching thedayvariable is the easier route to take. The test should look essentially the same as demonstrated above.