如何解决如何在测试运行时类型检查期间模拟 Python 类?
我有一些应用程序方法使用 @typeguard.typechecked
装饰器对传递的参数执行运行时检查:
class SalesDeal:
pass
@typechecked
def do_something(deal: SalesDeal):
pass
在一个测试中,我有一个伪类 FakeSalesDeal
,它为 SalesDeal
(实际上是一个非常复杂的类)实现了一个最小的模拟:
class FakeSalesDeal:
pass
def test_foo():
deal = FakeSalesDeal()
do_something(deal)
这个测试当然会失败,因为 @typechecked
装饰器会因不同的类而引发错误。
有没有办法模拟/伪造 FakeSalesDeal
的类以使测试通过?
解决方法
您可以使用 MagicMock
并将 spec
设置为 SalesDeal
而不是创建一个假类。
isinstance(mock,SalesDeal)
将是该模拟对象的 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
来自here的代码
因此,如果您使用适当的模拟,typechecked
应该不会给您带来任何问题。
我的最终解决方案:
class FakeSalesDeal(MagicMock):
pass
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。