Skip to content

Commit

Permalink
Fix error when building Pydantic models with nested Dict field (#107)
Browse files Browse the repository at this point in the history
  • Loading branch information
anthonyh209 committed Nov 4, 2022
1 parent 810f3c3 commit 51d9ef0
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# Changelog

[1.14.1]

- fix `ModelFactory` build ignore error when specifying an explicit dict for a nested `Dict` field @anthonyh209

[1.14.0]

- replace `Xeger` with local port to generate regexes.
Expand Down
4 changes: 2 additions & 2 deletions pydantic_factories/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
create_model_from_typeddict,
)
from pydantic.color import Color
from pydantic.fields import SHAPE_MAPPING
from pydantic.fields import SHAPE_DICT, SHAPE_MAPPING
from typing_extensions import _TypedDictMeta # type: ignore
from typing_extensions import TypeGuard, get_args, is_typeddict

Expand Down Expand Up @@ -215,7 +215,7 @@ def _is_pydantic_model_with_partial_fields(cls, field_name: str, model_field: "M
Returns:
A boolean determining whether the given field value is a pydantic model with missing kwargs.
"""
if model_field.shape != SHAPE_MAPPING and is_pydantic_model(model_field.type_):
if model_field.shape not in (SHAPE_DICT, SHAPE_MAPPING) and is_pydantic_model(model_field.type_):
field_kwargs = kwargs.get(field_name)

if isinstance(field_kwargs, list):
Expand Down
21 changes: 21 additions & 0 deletions tests/test_factory_child_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,3 +185,24 @@ class UpperSchemaFactory(ModelFactory):
assert "nested_key" in upper.nested
assert upper.nested["nested_key"].v == nested.v
assert upper.nested["nested_key"].z == nested.z


def test_factory_with_nested_dict() -> None:
"""Given a Pydantic Model with nested Dict field, When I build the model
using the factory passing only partial attributes, Then the model is
correctly built."""

class NestedSchema(BaseModel):
z: int

class UpperSchema(BaseModel):
nested: Mapping[str, NestedSchema]

class UpperSchemaFactory(ModelFactory):
__model__ = UpperSchema

nested = NestedSchema(z=0)
upper = UpperSchemaFactory.build(nested={"nested_dict": nested})

assert "nested_dict" in upper.nested
assert upper.nested["nested_dict"].z == nested.z

0 comments on commit 51d9ef0

Please sign in to comment.