Mypy: Mypy throws errors when MagicMock-ing a method

Created on 23 Apr 2019  路  2Comments  路  Source: python/mypy

Using Python 3.7 and MyPy 0.700.

When MagicMocking a method and then using MagicMock methods, mypy complains that the mocked method does not have the attribute "assert_called" and other MagicMock methods.
I'm not sure if it's at all possible for mypy to understand a method was monkey-patched like this, but it makes checking tests involving Mocks with mypy is not practical. Ideally, this code should not throw any errors.

For example:

from unittest.mock import MagicMock


class Foo:
    def bar(self) -> None:
        pass


foo = Foo()
foo.bar = MagicMock()
foo.bar()
foo.bar.assert_called()

When running Mypy, you get:

test.py:10: error: Cannot assign to a method
test.py:12: error: "Callable[[], None]" has no attribute "assert_called"

The first error is already discussed in https://github.com/python/mypy/issues/2427.
I couldn't find an issue discussing the second error.

false-positive feature priority-2-low

Most helpful comment

The context manager patch interface should work here:

from unittest.mock import MagicMock


class Foo:
    def bar(self) -> None:
        pass


foo = Foo()
with mock.patch.object(foo, "bar") as bar:
    foo.bar()
bar.assert_called()

All 2 comments

I could see how this can be problematic, but this is hard to support. First, we would need to add at least some basic generic support for monkey-patching.

The context manager patch interface should work here:

from unittest.mock import MagicMock


class Foo:
    def bar(self) -> None:
        pass


foo = Foo()
with mock.patch.object(foo, "bar") as bar:
    foo.bar()
bar.assert_called()
Was this page helpful?
0 / 5 - 0 ratings