Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: respect override of optional nested model fields #420

Merged
merged 6 commits into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion polyfactory/factories/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ def get_field_value( # noqa: C901, PLR0911, PLR0912
if cls.is_ignored_type(field_meta.annotation):
return None

if cls.should_set_none_value(field_meta=field_meta):
if field_build_parameters is None and cls.should_set_none_value(field_meta=field_meta):
return None

unwrapped_annotation = unwrap_annotation(field_meta.annotation, random=cls.__random__)
Expand Down
20 changes: 20 additions & 0 deletions tests/test_passing_build_args_to_child_factories.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from pydantic import BaseModel

from polyfactory.factories.pydantic_factory import ModelFactory
from polyfactory.field_meta import FieldMeta


class Address(BaseModel):
Expand Down Expand Up @@ -176,3 +177,22 @@ class DFactory(ModelFactory):
build_result = DFactory.build(factory_use_construct=False, **{"c": {"b": {"a": {"name": "test"}}}})
assert build_result
assert build_result.c.b.a.name == "test"


def test_factory_with_nested_optional_field_overrides_in_dict() -> None:
class MyChildModel(BaseModel):
name: str

class MyParentModel(BaseModel):
child: Optional[MyChildModel]

class MyParentModelFactory(ModelFactory):
__model__ = MyParentModel

@classmethod
def should_set_none_value(cls, field_meta: FieldMeta) -> bool:
return True

result = MyParentModelFactory.build(child={"name": "test"})
assert result.child is not None
assert result.child.name == "test"
Loading