Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在测试运行时类型检查期间模拟Python类?_Python_Python Mock_Python Typing - Fatal编程技术网

如何在测试运行时类型检查期间模拟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