pytest-dev/pytest-mock

mocker.patch.object behaves differently than it's unittest.mock counterpart

Closed this issue ยท 1 comments

Hey ๐Ÿ‘‹ I was writing some tests using pytest-mock and stumbled upon some unexpected behaviour while using mocker.patch.object.

While patch.object returns a mock object which can be used to assert on, mocker.patch.object seems to return a None value.

I created the following test to reproduce it:

def test_mocker_bug(mocker):
    class MyClass:
        def foo(self):
            return "foo"

    instance = MyClass()

    # This block passes without fail
    with patch.object(target=instance, attribute="foo", return_value="bar") as mock_foo:
        assert instance.foo() == "bar"
        mock_foo.assert_called()

    mock_foo.assert_called()

    # This block fails with an attribute error: "'NoneType' object has no attribute 'assert_called'"
    with mocker.patch.object(target=instance, attribute="foo", return_value="bar") as mocker_foo:
        assert instance.foo() == "bar"
        mocker_foo.assert_called()

    mocker_foo.assert_called()

Here are some environment details:

  • pytest: 7.4.4
  • pytest-mock: 3.14.0
  • python: 3.12.0

Took a closer look at some old issues and stumbled upon this section in the documentation:
https://pytest-mock.readthedocs.io/en/latest/usage.html#usage-as-context-manager

I guess I need to learn to read documentation better ๐Ÿ™ˆ

Anyway, closing this issue, sorry for the unnecessary noise ๐Ÿ™