diff --git a/environs.py b/environs.py index 4b60270..bc9d22b 100644 --- a/environs.py +++ b/environs.py @@ -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 @@ -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() diff --git a/tests/test_environs.py b/tests/test_environs.py index 3d54638..5c5afe0 100644 --- a/tests/test_environs.py +++ b/tests/test_environs.py @@ -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] @@ -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")