From 2c5806070612e64d249a5e1e0738e5ee5df5025e Mon Sep 17 00:00:00 2001 From: Bradley Golden Date: Wed, 3 Oct 2018 05:34:51 -0500 Subject: [PATCH] fix KeyError bug Fixes #7 and adds more thorough tests. --- .pre-commit-config.yaml | 1 - pytailor/__version__.py | 2 +- pytailor/config.py | 0 pytailor/tailor.py | 13 +++++++++---- pytest.ini | 2 ++ tests/test_tailor.py | 21 +++++++++++++++++++++ 6 files changed, 33 insertions(+), 6 deletions(-) create mode 100644 pytailor/config.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e80ef9b..2baa27d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,4 +1,3 @@ -fail_fast: true repos: - repo: https://github.com/ambv/black rev: stable diff --git a/pytailor/__version__.py b/pytailor/__version__.py index 9a2a49b..ae0c669 100644 --- a/pytailor/__version__.py +++ b/pytailor/__version__.py @@ -7,6 +7,6 @@ # |__| \/ \/ -VERSION = (0, 1, 2) +VERSION = (0, 1, 3) __version__ = ".".join(map(str, VERSION)) diff --git a/pytailor/config.py b/pytailor/config.py new file mode 100644 index 0000000..e69de29 diff --git a/pytailor/tailor.py b/pytailor/tailor.py index ceab283..3bb7d12 100644 --- a/pytailor/tailor.py +++ b/pytailor/tailor.py @@ -1,5 +1,6 @@ # -*- coding: utf-8 -*- import os +import warnings from .helpers import dotenv_to_dict, str_to_py @@ -68,7 +69,11 @@ def from_dotenv(self, path: str): self.store[name] = value def watch_env_var(self, name: str): - """Set configuration and watch a system wideenvironment variable.""" - value = os.environ[name] - mod_value = str_to_py(value) - self.env_store[name] = mod_value + """Set configuration and watch a system wide environment variable.""" + value = os.getenv(name) + if not value: + warn_msg = f"Environment variable '{name}' not found." + warnings.warn(warn_msg, RuntimeWarning) + else: + mod_value = str_to_py(value) + self.env_store[name] = mod_value diff --git a/pytest.ini b/pytest.ini index 66c02c1..156be98 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,3 +1,5 @@ [pytest] markers = unit +filterwarnings = + ignore::RuntimeWarning diff --git a/tests/test_tailor.py b/tests/test_tailor.py index 26543ff..db3c231 100644 --- a/tests/test_tailor.py +++ b/tests/test_tailor.py @@ -11,6 +11,10 @@ def setup_function(): + try: + del os.environ["FOO"] + except KeyError: + pass os.environ["FOO"] = "BAR" @@ -45,6 +49,23 @@ def test_from_object_and_then_dotenv(env_path): assert config["TESTING"] is False +def test_watch_env_var_that_doesnt_exist_raises_warning(): + config = Tailor() + with pytest.warns(RuntimeWarning) as warn: + config.watch_env_var("BAR") + + assert len(warn) == 1 + assert "not found" in warn[0].message.args[0] + + +def test_watch_env_var_that_doesnt_exist_but_exists_in_config_object(): + config = Tailor() + config["BAR"] = "BAZ" + config.watch_env_var("BAR") + assert "BAR" in config + assert config["BAR"] == "BAZ" + + def test_watch_env_var_and_change_after_watching(): config = Tailor() config.watch_env_var("FOO")