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

Accept dictionary default value for env.dict #76

Merged
merged 2 commits into from
May 16, 2019
Merged
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
9 changes: 9 additions & 0 deletions environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
# Python 2
import urlparse

try:
from collections.abc import Mapping
except ImportError:
# Python 2
from collections import Mapping

import marshmallow as ma
from dotenv import load_dotenv
from dotenv.main import _walk_to_root
Expand Down Expand Up @@ -108,6 +114,9 @@ def _preprocess_list(value, **kwargs):


def _preprocess_dict(value, **kwargs):
if isinstance(value, Mapping):
return value

subcast = kwargs.get("subcast")
return {
key.strip(): subcast(val.strip()) if subcast else val.strip()
Expand Down
12 changes: 12 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,12 @@ def test_list_cast(self, set_env, env):
set_env({"LIST": "1,2,3"})
assert env.list("LIST") == ["1", "2", "3"]

def test_list_with_default_from_string(self, set_env, env):
assert env.list("LIST", "1,2") == ["1", "2"]

def test_list_with_default_from_list(self, set_env, env):
assert env.list("LIST", ["1"]) == ["1"]

def test_list_with_subcast(self, set_env, env):
set_env({"LIST": "1,2,3"})
assert env.list("LIST", subcast=int) == [1, 2, 3]
Expand All @@ -100,6 +106,12 @@ def test_dict_with_subcast(self, set_env, env):
set_env({"DICT": "key1=1,key2=2"})
assert env.dict("DICT", subcast=int) == {"key1": 1, "key2": 2}

def test_dict_with_default_from_string(self, set_env, env):
assert env.dict("DICT", "key1=1,key2=2") == {"key1": "1", "key2": "2"}

def test_dict_with_default_from_dict(self, set_env, env):
assert env.dict("DICT", {"key1": "1"}) == {"key1": "1"}

def test_decimat_cast(self, set_env, env):
set_env({"DECIMAL": "12.34"})
assert env.decimal("DECIMAL") == Decimal("12.34")
Expand Down