Skip to content

Commit

Permalink
feat: support annotation with Constraints (#411)
Browse files Browse the repository at this point in the history
  • Loading branch information
guacs authored Oct 18, 2023
1 parent 0631d80 commit e1f7a47
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 5 additions & 1 deletion polyfactory/field_meta.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from dataclasses import asdict, is_dataclass
from typing import TYPE_CHECKING, Any, Literal, Pattern, TypedDict, cast

from typing_extensions import get_args, get_origin
from typing_extensions import Mapping, get_args, get_origin

from polyfactory.collection_extender import CollectionExtender
from polyfactory.constants import (
Expand Down Expand Up @@ -183,6 +183,10 @@ def parse_constraints(cls, metadata: list[Any]) -> "Constraints":
constraints["pattern"] = "[[:digit:]]"
elif is_dataclass(value) and (value_dict := asdict(value)) and ("allowed_schemes" in value_dict):
constraints["url"] = {k: v for k, v in value_dict.items() if v is not None}
# This is to support `Constraints`, but we can't do a isinstance with `Constraints` since isinstance
# checks with `TypedDict` is not supported.
elif isinstance(value, Mapping):
constraints.update(value)
else:
constraints.update(
{
Expand Down
9 changes: 9 additions & 0 deletions tests/constraints/test_get_field_value_constraints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from typing import FrozenSet, List, Set, Tuple, Type, Union, cast

import pytest
from typing_extensions import Annotated

from polyfactory.factories.base import BaseFactory
from polyfactory.field_meta import Constraints, FieldMeta
Expand Down Expand Up @@ -57,3 +58,11 @@ def test_date() -> None:

assert value >= ge_date
assert value <= le_date


def test_constraints_parsing() -> None:
constraints = Constraints(min_length=10)
annotation = Annotated[str, constraints]
field_meta = FieldMeta.from_type(annotation)

assert field_meta.constraints == constraints

0 comments on commit e1f7a47

Please sign in to comment.