如何在测试运行时类型检查期间模拟Python类?
我有一些应用程序方法,它使用如何在测试运行时类型检查期间模拟Python类?,python,python-mock,python-typing,Python,Python Mock,Python Typing,我有一些应用程序方法,它使用@typeguard.typechecked装饰程序对传递的参数执行运行时检查: class SalesDeal: pass @typechecked def do_something(deal: SalesDeal): pass 在一个测试中,我有一个伪类FakeSalesDeal,它为SalesDeal实现了一个最小的模拟(实际上这是一个非常复杂的类): 此测试当然会失败,因为@typechecked装饰程序将由于不同的类而引发错误 是否有办法模
@typeguard.typechecked
装饰程序对传递的参数执行运行时检查:
class SalesDeal:
pass
@typechecked
def do_something(deal: SalesDeal):
pass
在一个测试中,我有一个伪类FakeSalesDeal
,它为SalesDeal
实现了一个最小的模拟(实际上这是一个非常复杂的类):
此测试当然会失败,因为@typechecked
装饰程序将由于不同的类而引发错误
是否有办法模拟/伪造
FakeSalesDale
的类以通过测试?您可以使用MagicMock
,将spec
设置为SalesDale
,而不是创建假类
isinstance(mock,SalesDeal)
对于该mock对象将为True
&您应该能够绕过类型检查
from unittest.mock import MagicMock
# ...
def test_foo():
deal = MagicMock(spec=SalesDeal)
print(isinstance(deal, SalesDeal))
do_something(deal)
test_foo()
这张照片是:
True
&不会抛出任何类型检查错误
这是因为typechecked
显式检查传递给以下对象的Mock
对象:
if expected_type is Any or isinstance(value, Mock):
return
代码来自
因此,如果您使用正确的模拟,typechecked
应该不会给您带来任何问题。我的最终解决方案:
class FakeSalesDeal(MagicMock):
pass
您是否考虑过让
FakeSalesDeal
从SalesDeal
继承,并用一组模拟值初始化它(避免SalesDeal
的复杂方面)?是的,这也很有效。谢谢您的指针。也可以从MagicMock继承并通过类型检查..某种程度上是通过传递,但它解决了问题。
class FakeSalesDeal(MagicMock):
pass