polyfactory icon indicating copy to clipboard operation
polyfactory copied to clipboard

Bug: Wrong type date generated for annotated datetime in pydantic factory

Open felixpatzelt opened this issue 5 months ago • 1 comments

Description

When using an annotated datetime type in a pydantic model, polyfactory generates random dates instead of random datetimes. This leads to unexpected results:

  • time is always set to midnight
  • breaks custom validators relying on e.g. tzinfo

URL to code causing the issue

No response

MCVE

from typing import Optional, Annotated
import datetime
from pydantic import BaseModel, Field, BeforeValidator
from polyfactory.factories.pydantic_factory import ModelFactory


def validate_datetime(value: datetime.datetime) -> datetime.datetime:
    print(type(value))
    assert value.tzinfo == datetime.timezone.utc
    return value


ValidatedDatetime = Annotated[
    datetime.datetime, BeforeValidator(validate_datetime)
]


class MyModel(BaseModel):
    dt: ValidatedDatetime = Field(
        gt=datetime.datetime(2022, 1, 1, tzinfo=datetime.timezone.utc)
    )


class MyModelFactory(ModelFactory[MyModel]):
    pass


MyModelFactory.build()

# => Prints: <class 'datetime.date'>
# => Returns error: AttributeError: 'datetime.date' object has no attribute 'tzinfo'

Steps to reproduce

Create an annotated datetime type
Create a pydantic model with a field of the annotated datetime type
Create a ModelFactory for the pydantic model
Call ModelFactory.build()

Screenshots

No response

Logs


Release Version

polyfactory 2.22.1

Platform

  • [ ] Linux
  • [x] Mac
  • [ ] Windows
  • [ ] Other (Please specify in the description above)

felixpatzelt avatar Jul 17 '25 11:07 felixpatzelt

Thanks for reporting!

Currently only have this implemented for dates https://github.com/litestar-org/polyfactory/blob/main/polyfactory/factories/base.py#L726-L734. PRs welcome to update

adhtruong avatar Jul 19 '25 07:07 adhtruong