litestar-org/polyfactory

Bug: constraints not working in pydantic v2 (when a `Union` is used)

AIGeneratedUsername opened this issue · 2 comments

Preface

There was a confirmed bug #307 but it was not completely fixed.

Using Annotated was fixed but using Annotated[<type>, <...>] | None still fails.

Reproducible sample

from typing import Annotated
from annotated_types import Ge, Le
from pydantic import BaseModel

LongLat = tuple[Annotated[float, Ge(-180), Le(180)], Annotated[float, Ge(-90), Le(90)]]


class Location(BaseModel):
    long_lat: LongLat | None


from polyfactory.factories.pydantic_factory import ModelFactory


class LocationFactory(ModelFactory[Location]):
    __model__ = Location


# Run multiple times because we have a union of types and we must trigger a not-None option.
for _ in range(100):
    LocationFactory.build()

Error output

long_lat.0
  Input should be greater than or equal to -180 [type=greater_than_equal, input_value=-7760968059339.52, input_type=float]
    For further information visit https://errors.pydantic.dev/2.1/v/greater_than_equal
long_lat.1
  Input should be less than or equal to 90 [type=less_than_equal, input_value=7865.80622030079, input_type=float]
    For further information visit https://errors.pydantic.dev/2.1/v/less_than_equal

Versions

Name: polyfactory 
Version: 2.7.0

Funding

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
Fund with Polar

Is this still happening?

Is this still happening?

Yes, I just verified on the "main" branch.