Mock instance attributes without instance

  mocking, pytest, pytest-mock, python

I would like to test by mocking an instance’s attribute, but I do not have access to the instance beforehand. How can I mock the attribute without it? Here is my minimum reproducible code.

# test.py

class Foo:
    def __init__(self, x):
        self.x = x

def bar():
    return Foo(1).x + 1

def test_bar(mocker):
    mocker.patch('test.Foo.x', 2)
    assert bar() == 3
$ pytest test.py
FAILED test.py::test_bar - AttributeError: <class 'test.Foo'> does not have the attribute 'x'

This makes sense since the Foo class doesn’t have an x, only instances. If I add a kwarg mocker.patch('test.Foo.x', 2, create=True) I then get this

$ pytest test.py
FAILED test.py::test_bar - assert 2 == 3

since Foo.x will get mocked but overridden when the instance later sets self.x = x.

Source: Python Questions

LEAVE A COMMENT