Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perform type validation on string var_type for benefit of default value #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions envs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def validate_boolean(value):

class Env(object):
valid_types = {
'string': None,
'string': str,
'boolean': validate_boolean,
'list': list,
'tuple': tuple,
Expand All @@ -56,16 +56,20 @@ def __call__(self, key, default=None, var_type='string', allow_none=True):
if not allow_none:
raise EnvsValueException('{}: Environment Variable Not Set'.format(key))
return value
return self.validate_type(value, self.valid_types[var_type], key)
return self.validate_type(value, var_type, key)

def validate_type(self, value, klass, key):
if not klass:
return value
def validate_type(self, value, var_type, key):
klass = self.valid_types[var_type]
if klass in (validate_boolean, Decimal):
return klass(value)
if isinstance(value, klass):
return value
return klass(ast.literal_eval(value))
try:
return klass(ast.literal_eval(value))
except ValueError as e:
raise TypeError(
f'Could not resolve value ({value}) as var_type ({var_type}) for key {key}'
) from e


env = Env()
11 changes: 10 additions & 1 deletion envs/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,16 @@ def test_defaults(self):
self.assertEqual(env('HELLO', 'true', var_type='boolean'), True)
self.assertEqual(env('HELLO', Decimal('3.14'), var_type='decimal'), Decimal('3.14'))

def test_defaults_type_mismatch(self):
# Setting a default int with an implicit var_type of string should fail
# (otherwise default type is different than overridden type and that
# can cause problems in client code)
with self.assertRaises(TypeError):
env('HELLO', 5)
# Setting a default int with an explicit var_type of not-int should fail
with self.assertRaises(TypeError):
env('HELLO', 5, var_type='dict')

def test_without_defaults_allow_none(self):
self.assertEqual(env('HELLO'), None)
self.assertEqual(env('HELLO', var_type='integer'), None)
Expand Down Expand Up @@ -198,4 +208,3 @@ def test_list_envs():

if __name__ == '__main__':
unittest.main()