如何键入包含在 Mock 中的提示对象?

How to type hint object wrapped in a Mock?

我通常使用 unittest.mock.Mockwraps 功能来创建功能齐全的间谍对象。

这是一个在 运行:

时运行良好的例子
from threading import Event
from typing import Union
from unittest.mock import Mock

spy_event: Union[Mock, Event] = Mock(wraps=Event())

spy_event.set()
assert spy_event.is_set()

# How can I type hint so this error doesn't show up from mypy?
spy_event.set.assert_called_once_with()  # error: Item "function" of
# "Union[Any, Callable[[], None]]" has no attribute "assert_called_once_with"

您可以看到,Union[Mock, Event] 类型提示不起作用。

如何正确键入提示包裹在 Mock 中的对象?


版本

Python==3.8.6
mypy==0.812

spy_event 只是一个 Mock。将其注释为 Mock:

spy_event: Mock = Mock(wraps=Event())

我不知道你为什么要这么做 Union - 你可能误解了 Union 的意思。