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 Required and NonRequired annotations #422

Merged
merged 4 commits into from
Oct 21, 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
38 changes: 26 additions & 12 deletions polyfactory/factories/typed_dict_factory.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
from __future__ import annotations

from typing import Any, Generic, TypeVar

from typing_extensions import TypeGuard, _TypedDictMeta, get_type_hints, is_typeddict # type: ignore[attr-defined]
from typing import Any, Generic, TypeVar, get_args

from typing_extensions import ( # type: ignore[attr-defined]
NotRequired,
Required,
TypeGuard,
_TypedDictMeta, # pyright: ignore[reportGeneralTypeIssues]
get_origin,
get_type_hints,
is_typeddict,
)

from polyfactory.constants import DEFAULT_RANDOM
from polyfactory.factories.base import BaseFactory
Expand Down Expand Up @@ -35,13 +43,19 @@ def get_model_fields(cls) -> list["FieldMeta"]:
"""
model_type_hints = get_type_hints(cls.__model__, include_extras=True)

fields_meta: list["FieldMeta"] = [
FieldMeta.from_type(
annotation=annotation,
random=DEFAULT_RANDOM,
name=field_name,
default=getattr(cls.__model__, field_name, Null),
field_metas: list[FieldMeta] = []
for field_name, annotation in model_type_hints.items():
origin = get_origin(annotation)
if origin in (Required, NotRequired):
annotation = get_args(annotation)[0] # noqa: PLW2901

field_metas.append(
FieldMeta.from_type(
annotation=annotation,
random=DEFAULT_RANDOM,
name=field_name,
default=getattr(cls.__model__, field_name, Null),
),
)
for field_name, annotation in model_type_hints.items()
]
return fields_meta

return field_metas
3 changes: 2 additions & 1 deletion tests/constraints/test_int_constraints.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from random import Random

import pytest
from hypothesis import assume, given
from hypothesis import HealthCheck, assume, given, settings
from hypothesis.strategies import integers

from polyfactory.exceptions import ParameterException
Expand Down Expand Up @@ -55,6 +55,7 @@ def test_handle_constrained_int_handles_lt(maximum: int) -> None:
assert result < maximum


@settings(suppress_health_check=(HealthCheck.filter_too_much,))
guacs marked this conversation as resolved.
Show resolved Hide resolved
@given(
integers(min_value=1, max_value=10),
integers(min_value=1, max_value=10),
Expand Down
25 changes: 24 additions & 1 deletion tests/test_typeddict_factory.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import Dict, List, Optional

from annotated_types import Ge
from pydantic import BaseModel
from typing_extensions import TypedDict
from typing_extensions import Annotated, NotRequired, Required, TypedDict

from polyfactory.factories import TypedDictFactory
from polyfactory.factories.pydantic_factory import ModelFactory
Expand Down Expand Up @@ -44,3 +45,25 @@ class MyFactory(ModelFactory[MyModel]):
assert result.td["name"]
assert result.td["list_field"][0]
assert type(result.td["int_field"]) in (type(None), int)


def test_typeddict_with_required_and_non_required_fields() -> None:
class TypedDictModel(TypedDict):
id: Required[int]
name: NotRequired[str]
guacs marked this conversation as resolved.
Show resolved Hide resolved
annotated: Required[Annotated[int, Ge(100)]]
list_field: List[Dict[str, int]]
optional_int: Required[Optional[int]]

class TypedDictModelFactory(TypedDictFactory[TypedDictModel]):
__model__ = TypedDictModel

result = TypedDictModelFactory.build()

assert isinstance(result["id"], int)
assert isinstance(result["annotated"], int)
assert result["annotated"] >= 100
assert isinstance(result["list_field"], list)
assert isinstance(result["optional_int"], (type(None), int))
assert "name" in result
assert isinstance(result["name"], str)
Loading