我有一个相当有趣的问题。我正在尝试模拟一个可以通过内部验证的类,并且在实例化时会返回一个 magicmock 实例。
例如,我有一个 pydantic 模型可以验证以下字段:
from typing import Type
from pydantic import BaseModel
class SomeClass:
pass
class SubSomeClass(SomeClass):
pass
class OtherClass:
pass
class SomeModel(BaseModel):
cls: Type[SomeClass]
# here I can put either `SomeClass` or its subclasses
validated_some = SomeModel(cls=SubSomeClass)
# this would cause ValidationError
SomeModel(cls=OtherClass)
"""
pydantic.error_wrappers.ValidationError: 1 validation error for SomeModel
cls
subclass of SomeClass expected (type=type_error.subclass; expected_class=SomeClass)
"""
现在在我的测试中,我试图模拟我的SomeClass
using MagicMock
,但我无法创建一个模拟的类对象,它就像SomeClass
.
我尝试了以下方法:
>>> type(Mock(spec=SomeClass))
<class 'unittest.mock.Mock'> # doesn't pass validation
class MockSomeClass(SomeClass, MagicMock):
"""Mocked SomeClass"""
def __init__(self, *args, **kwargs):
pass
实例化时不返回MagicMock
实例,即MockSomeClass()
。
基本上我需要一些类似的东西:
>>> type(mocked_some_class)
<class 'type'>
>>> import inspect
>>> inspect.getmro(mocked_some_class)
(..., <class '__main__.SomeClass'>, ...)
>>> mocked_some_class()
<MagicMock id='...'>