Skip to content

Commit

Permalink
Json non str default (#309)
Browse files Browse the repository at this point in the history
* Accept non str values as default json parser value

* Add type checking when importing default json.

* Add tests to default json validation.

* Update changelog

---------

Co-authored-by: Tom <tomgrin10@gmail.com>
Co-authored-by: Brunno Vanelli <brunnovanelli@gmail.com>
  • Loading branch information
3 people committed Jan 8, 2024
1 parent a31c0ca commit 7d11d78
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 10.1.0 (unreleased)

Features:

- Allow `default` for `env.json` to be a `dict` or `list` ([#240](https://github.com/sloria/environs/pull/240)).
Thanks [tomgrin10](https://github.com/tomgrin10) and [bvanelli](https://github.com/bvanelli) for the PRs.

## 10.0.0 (2023-12-15)

Features:
Expand Down
9 changes: 7 additions & 2 deletions environs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,9 +231,14 @@ def _preprocess_dict(
}


def _preprocess_json(value: str, **kwargs):
def _preprocess_json(value: typing.Union[str, typing.Mapping, typing.List], **kwargs):
try:
return pyjson.loads(value)
if isinstance(value, str):
return pyjson.loads(value)
elif isinstance(value, dict) or isinstance(value, list) or value is None:
return value
else:
raise ma.ValidationError("Not valid JSON.")
except pyjson.JSONDecodeError as error:
raise ma.ValidationError("Not valid JSON.") from error

Expand Down
7 changes: 7 additions & 0 deletions tests/test_environs.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,13 @@ def test_invalid_json_raises_error(self, set_env, env):
env.json("JSON")
assert "Not valid JSON." in exc.value.args[0]

def test_json_default(self, set_env, env):
assert env.json("JSON", {"foo": "bar"}) == {"foo": "bar"}
assert env.json("JSON", ["foo", "bar"]) == ["foo", "bar"]
with pytest.raises(environs.EnvError) as exc:
env.json("JSON", int) # a builtin is not a valid json
assert "Not valid JSON." in exc.value.args[0]

def test_datetime_cast(self, set_env, env):
dtime = dt.datetime.utcnow()
set_env({"DTIME": dtime.isoformat()})
Expand Down

0 comments on commit 7d11d78

Please sign in to comment.