Skip to content

Instantly share code, notes, and snippets.

@ross-spencer
Created January 1, 2021 21:14
Show Gist options
  • Save ross-spencer/b30115cea336016e34897bb4e1d4db04 to your computer and use it in GitHub Desktop.
Save ross-spencer/b30115cea336016e34897bb4e1d4db04 to your computer and use it in GitHub Desktop.
Example code for wrapping os.environ.get()
"""get_envi module
Consistently retrieve environment variables to use in your modules.
Try-it-out with:
`python -m pytest envi.py`
"""
from os import environ
import pytest
def is_true(env_str):
return env_str.lower() in ["true", "yes", "on", "1"]
def get_envvar(name, default, cast=False):
"""Wraps os.environ.get to manage type consistency.
:param name: environment variable name to get.
:param default: default to use when name can't be got.
:param cast: python type to cast the return value to, e.g. when the
plain-string is just fine.
"""
if not cast:
return environ.get(name, default)
envvar = environ.get(name, default)
if cast == bool:
return is_true(envvar)
try:
return cast(envvar)
except ValueError:
return default
@pytest.mark.parametrize(
"return_value, default, cast, expected_result",
[
# Return True correctly.
("true", "False", bool, True),
# Return False correctly.
("not true", "", bool, False),
# Return a plain-string.
("some_setting", "", None, "some_setting"),
# Return a properly cast int.
(1, "2", int, 1),
# Return the default for a ValueError for an int.
("string", 42, int, 42),
# etc.
],
)
def test_get_envvar(return_value, default, cast, expected_result, mocker):
"""Test various different environment return values"""
if cast is None:
mock = mocker.patch("os.environ.get", return_value=return_value)
assert get_envvar("value", "") == expected_result
else:
mock = mocker.patch("os.environ.get", return_value=return_value)
assert get_envvar("value", default, cast) is expected_result
assert mock.called_once()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment