adamchainz / time-machine

Travel through time in your tests.
MIT License
729 stars 34 forks source link

time_machine.travel doesn't work with Pydantic 2 #438

Closed MrSampson closed 7 months ago

MrSampson commented 8 months ago

Python Version

3.11.7

pytest Version

7.4.4

Package Version

2.14.1

Description

When using pydantic 2.6.4 Field default values, time machine.travel doesn't seem to have any affect.

import datetime as dt
import time_machine
from pydantic import BaseModel, Field

class Test(BaseModel):

    time: dt.datetime = Field(default=dt.datetime.now(), validate_default=True)

@time_machine.travel(dt.datetime(2020, 1, 10, 10, 30))
def test_init__default():
    result = Test()
    assert result.time == dt.datetime(2020, 1, 10, 10, 30)

After executing the test, the result.time will be the current system time.

adamchainz commented 7 months ago

You’re calling dt.datetime.now() at import time, which provides a set time to Pydantic. There’s no later function call for time-machine to patch. I think you instead want default_factory=dt.datetime.now (docs).

MrSampson commented 7 months ago

Thank you! I didn't even know that existed.