Skip to content

Commit

Permalink
Fix Json strategy serialization failure
Browse files Browse the repository at this point in the history
When generating a pydantic model having nested Json fields with
hypothesis, a JSON serialization exception was raised.
  • Loading branch information
SergioSim committed Jul 20, 2022
1 parent 50bc758 commit 31ab8be
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 1 deletion.
1 change: 1 addition & 0 deletions changes/4005-sergiosim.md
@@ -0,0 +1 @@
Fix Json strategy serialization failure
4 changes: 3 additions & 1 deletion pydantic/_hypothesis_plugin.py
Expand Up @@ -34,6 +34,7 @@
import pydantic
import pydantic.color
import pydantic.types
from pydantic.utils import lenient_issubclass

# FilePath and DirectoryPath are explicitly unsupported, as we'd have to create
# them on-disk, and that's unsafe in general without being told *where* to do so.
Expand Down Expand Up @@ -222,8 +223,9 @@ def resolve_json(cls): # type: ignore[no-untyped-def]
base=st.one_of(st.none(), st.booleans(), st.integers(), finite, st.text()),
extend=lambda x: st.lists(x) | st.dictionaries(st.text(), x), # type: ignore
)
inner_type = getattr(cls, 'inner_type', None)
return st.builds(
json.dumps,
cls.inner_type.json if lenient_issubclass(inner_type, pydantic.BaseModel) else json.dumps,
inner,
ensure_ascii=st.booleans(),
indent=st.none() | st.integers(0, 16),
Expand Down
1 change: 1 addition & 0 deletions tests/test_hypothesis_plugin.py
Expand Up @@ -67,6 +67,7 @@ class JsonModel(pydantic.BaseModel):
json_str: pydantic.Json[str]
json_int_or_str: pydantic.Json[typing.Union[int, str]]
json_list_of_float: pydantic.Json[typing.List[float]]
json_pydantic_model: pydantic.Json[pydantic.BaseModel]

class ConstrainedNumbersModel(pydantic.BaseModel):
conintt: pydantic.conint(gt=10, lt=100)
Expand Down

0 comments on commit 31ab8be

Please sign in to comment.