I usually can patch methods of normal objects using pytest monkeypatch. However when I try with a pydantic.BaseModel it fails.
from pydantic import BaseModel
class Person(BaseModel):
name: str
age: int
def intro(self) -> str:
return f"I am {self.name}, {self.age} years old."
def test_person_intro(monkeypatch):
p = Person(name='Joe', age=20)
monkeypatch.setattr(p, 'intro', lambda: 'patched intro')
assert p.intro() == 'patched intro'
Raises:
monkeypatch = <_pytest.monkeypatch.MonkeyPatch object at 0x10f0d3040>
def test_intro(monkeypatch):
p = Person(name='Joe', age=20)
> monkeypatch.setattr(p, 'intro', lambda: 'patched intro')
- - - - - - - - - - - - - - - - - - - - -
> ???
E ValueError: "Person" object has no field "intro"
pydantic/main.py:422: ValueError