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 Apr 25, 2022
1 parent 8997cc5 commit f669c91
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
13 changes: 11 additions & 2 deletions pydantic/_hypothesis_plugin.py
Expand Up @@ -27,7 +27,7 @@
import json
import math
from fractions import Fraction
from typing import Callable, Dict, Type, Union, cast, overload
from typing import Any, Callable, Dict, Type, Union, cast, overload

import hypothesis.strategies as st

Expand Down Expand Up @@ -212,6 +212,15 @@ def inner(f): # type: ignore
# Type-to-strategy resolver functions


def is_base_model(cls: Any) -> bool:
"""Returns True if the given class is a subclass of the pydantic BaseModel."""

try:
return issubclass(cls, pydantic.BaseModel)
except TypeError:
return False


@resolves(pydantic.JsonWrapper)
def resolve_json(cls): # type: ignore[no-untyped-def]
try:
Expand All @@ -223,7 +232,7 @@ def resolve_json(cls): # type: ignore[no-untyped-def]
extend=lambda x: st.lists(x) | st.dictionaries(st.text(), x), # type: ignore
)
return st.builds(
json.dumps,
cls.inner_type.json if is_base_model(getattr(cls, 'inner_type', None)) 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 f669c91

Please sign in to comment.