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: handle cases where 'init=False' for dataclasses and attrs models #433

Merged
merged 2 commits into from
Nov 1, 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
3 changes: 3 additions & 0 deletions polyfactory/factories/attrs_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ def get_model_fields(cls) -> list[FieldMeta]:
fields = attrs.fields(cls.__model__)

for field in fields:
if not field.init:
continue

annotation = none_type if field.type is None else field.type

default = field.default
Expand Down
3 changes: 3 additions & 0 deletions polyfactory/factories/dataclass_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ def get_model_fields(cls) -> list["FieldMeta"]:
model_type_hints = get_type_hints(cls.__model__, include_extras=True)

for field in fields(cls.__model__): # type: ignore[arg-type]
if not field.init:
continue

if field.default_factory and field.default_factory is not MISSING:
default_value = field.default_factory()
elif field.default is not MISSING:
Expand Down
11 changes: 11 additions & 0 deletions tests/test_attrs_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,3 +180,14 @@ class FooFactory(AttrsFactory[Foo]):
foo = FooFactory.build()

assert isinstance(foo.int_field, int)


def test_with_init_false() -> None:
@define
class Foo:
foo: int = attrs.field(init=False)

class FooFactory(AttrsFactory[Foo]):
__model__ = Foo

assert FooFactory.build()
13 changes: 13 additions & 0 deletions tests/test_dataclass_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,16 @@ class FooFactory(DataclassFactory[Foo]): # type:ignore[valid-type]

foo = FooFactory.build()
assert isinstance(foo, Foo)


def test_dataclass_with_init_false() -> None:
@vanilla_dataclass
class VanillaDC:
id_: int = field(init=False)

class MyFactory(DataclassFactory[VanillaDC]):
__model__ = VanillaDC

result = MyFactory.build()

assert result
Loading