litestar-org / litestar-org/polyfactory

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

Open
#734 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug good first issue
Dominant language
Python
Stars
1.5k
Forks
120
PR merge metrics
No merged PRs in 30d

Description

### 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

```python
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:
# => Returns error: AttributeError: 'datetime.date' object has no attribute 'tzinfo'
```

### Steps to reproduce

```bash
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

```bash

```

### Release Version

polyfactory 2.22.1

### Platform

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the MCVE through polyfactory.factories.pydantic_factory.ModelFactory and MyModelFactory.build(), then trace how the annotated datetime field is handled. Done means the generated value is a datetime rather than a date, retains the expected timezone information, and allows the validator to complete successfully.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
testing
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
68/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.