Skip to content

Commit

Permalink
Merge pull request #2 from sionide21/raise_error_if_missing
Browse files Browse the repository at this point in the history
If variable is required, raise an error if missing
  • Loading branch information
schwuk committed Dec 30, 2013
2 parents 72d777f + d7e05fa commit 1a70354
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions getenv.py
Expand Up @@ -2,18 +2,27 @@
import ast
import unittest

try:
from django.core.exceptions import ImproperlyConfigured
except ImportError:
# If they aren't using django, define our own error
class ImproperlyConfigured(Exception): pass

def env(key, default=None):

def env(key, default=None, required=False):
"""
Retrieves environment variables and returns Python natives. The (optional)
default will be returned if the environment variable does not exist.
"""
value = os.environ.get(key, default)

try:
value = os.environ[key]
return ast.literal_eval(value)
except (SyntaxError, ValueError):
return value
except KeyError:
if default or not required:
return default
raise ImproperlyConfigured("Missing required environment variable '%s'" % key)


class TestEnv(unittest.TestCase):
Expand All @@ -32,6 +41,19 @@ def test_missing_var_with_default(self):
"""
self.assertEqual(env("FRABJOUS", "day"), "day")

def test_missing_required_var_with_no_default(self):
"""
If we specify a non-existent environment variable that's required, we get an error
"""
self.assertRaises(ImproperlyConfigured, env, "FRABJOUS", required=True)

def test_missing_required_var_with_default(self):
"""
If for whatever reason, we specify a non-existent environment variable that's required, but give it a
default we'll get that default back.
"""
self.assertEqual(env("FRABJOUS", "day", required=True), "day")

def test_var(self):
"""
If the environment variable is present, we'll get the value back.
Expand Down

0 comments on commit 1a70354

Please sign in to comment.