2 years ago
#69550
Gros Lalo
Not able to patch datetime.utcnow in a custom type based on Pydantic's BaseModel
I am not able to patch datetime.utcnow
correctly and I am wondering what could be wrong. The code below illustrates the idea:
# In a file called 'my_module.py'
from datetime import datetime
from pydantic import BaseModel, Field
class Pet(BaseModel):
ts: datetime = Field(default_factory=datetime.utcnow)
And the corresponding test code is:
from datetime import datetime
from unittest.mock import patch
from my_module import Pet
@patch("my_module.datetime")
def test_pet(mocked):
timestamp = datetime(2000, 10, 10, 21, 50)
mocked.utcnow.return_value = timestamp
pet = Pet()
assert pet.ts == timestamp
# pet.ts is getting current date and time :/
When I run pytest
, the pet.ts
does not get assigned the patched timestamp. Instead it is getting the current date and time. I am wondering what could be wrong/missing in my setup. Would anyone have an idea?
I am using the following tools:
Python 3.9.8
pydantic 1.9.0
pytest 6.25
python
pytest
pydantic
0 Answers
Your Answer