Search code examples
pythonpython-typingmypy

How to type hint object wrapped in a Mock?


I commonly use unittest.mock.Mock's wraps functionality to create fully-functioning spy objects.

Here's an example that works fine when run:

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"

You can see, the Union[Mock, Event] type hint isn't working out.

How can I properly type hint an object wrapped in a Mock?


Versions

Python==3.8.6
mypy==0.812

Solution

  • spy_event is just a Mock. Annotate it as a Mock:

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

    I don't know why you did that Union thing - you may be misunderstanding what Union means.