Skip to content

Mypy throws errors when MagicMock-ing a method #6713

Closed
@MatanRubin

Description

@MatanRubin

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 #2427.
I couldn't find an issue discussing the second error.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions