How to mock property

I am asking how to model a class property in a unit test using Python 3. I tried the following, which makes sense to me, following the documentation, but this does not work:

foo.py:

class Foo():
    @property
    def bar(self):
        return 'foobar'


def test_foo_bar(mocker):
    foo = Foo()
    mocker.patch.object(foo, 'bar', new_callable=mocker.PropertyMock)
    print(foo.bar)

I installed pytestand pytest_mockrun the test as follows:

pytest foo.py

I got the following error:

>       setattr(self.target, self.attribute, new_attr)
E       AttributeError: can't set attribute

/usr/lib/python3.5/unittest/mock.py:1312: AttributeError

I expect the test to run without errors.

+6
source share
3 answers

, . " " ( Python )

- with, :

def test_foo_bar(mock):
    foo = Foo()
    with mock.patch(__name__ + "Foo.bar", new=mocker.PropertyMock)
        print(foo.bar)
+8

, - :

def test_foo_bar():
    foo = Foo()
    type(foo).bar = 'anything you want'
    print(foo.bar)

bar, .

0

You are missing @bar.setter.

@bar.setter
def bar(self, foo):
    self.__bar = foo
-1
source

Source: https://habr.com/ru/post/1671923/


All Articles