Skip to content

Commit

Permalink
Test passing internal types as default
Browse files Browse the repository at this point in the history
  • Loading branch information
sloria committed Jan 6, 2025
1 parent 279537f commit f343497
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## 12.0.0 (unreleased)

Features:

- `Env.enum` allows passing an `Enum` as `default`.

Other changes:

- Support marshmallow 4.
- Support Python 3.9-3.13.
- _Backwards-incompatible_: Make `Field` classes private. Users should
Expand Down
3 changes: 3 additions & 0 deletions src/environs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,9 @@ def _preprocess_json(value: str | typing.Mapping | list, **kwargs):


def _enum_parser(value, type: type[_EnumT], ignore_case: bool = False) -> _EnumT:
if isinstance(value, type):
return value

invalid_exc = ma.ValidationError(f"Not a valid '{type.__name__}' enum.")

if not ignore_case:
Expand Down
23 changes: 23 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,24 @@ def test_date_cast(self, set_env, env):
set_env({"DATE": date.isoformat()})
assert env.date("DATE") == date

@pytest.mark.xfail(
MARSHMALLOW_VERSION.major < 4,
reason="marshmallow 3 does not allow all fields to accept internal types",
)
@pytest.mark.parametrize(
("method_name", "value"),
[
pytest.param("timedelta", dt.timedelta(seconds=42), id="timedelta"),
pytest.param("date", dt.date(2020, 1, 1), id="date"),
pytest.param("datetime", dt.datetime(2020, 1, 1, 1, 2, 3), id="datetime"),
pytest.param("time", dt.time(1, 2, 3), id="time"),
pytest.param("uuid", uuid.uuid4(), id="uuid"),
],
)
def test_default_can_be_set_to_internal_type(self, env, method_name: str, value):
method = getattr(env, method_name)
assert method("NOTFOUND", value) == value

def test_timedelta_cast(self, set_env, env):
# default values
assert env.timedelta("TIMEDELTA", "42") == dt.timedelta(seconds=42)
Expand Down Expand Up @@ -364,6 +382,11 @@ def test_invalid_enum_ignore_case(self, set_env, env):
with pytest.raises(environs.EnvError):
assert env.enum("DAY", type=DayEnum, ignore_case=True)

def test_enum_default(self, env: environs.Env):
assert (
env.enum("NOTFOUND", type=DayEnum, default=DayEnum.SUNDAY) == DayEnum.SUNDAY
)


class TestEnvFileReading:
def test_read_env(self, env):
Expand Down

0 comments on commit f343497

Please sign in to comment.