4

I have a project that I need to mock a property using the mocker fixture. Its using pytest and pytest-mock:

pip install pytest pytest-mock

A simple example of the problem:

I have the foo class in the foo.py file:

class Foo:
    @property
    def bar(self):
        return "x"

And I have to test it mocking the property bar:

import foo

def test_foo(mocker):
    mocker.patch("foo.Foo.bar", return_value="y")
    f = foo.Foo()
    assert f.bar == "y"

But when I patch it, the bar behaves like a callable and not like an attribute, how to fix this?

MrBean Bremen
  • 14,916
  • 3
  • 26
  • 46
Cristiano Araujo
  • 1,632
  • 2
  • 21
  • 32

1 Answers1

5

I was able to so using the mocker.PropertyMock just like @idjaw comment.

import foo


def test_foo(mocker):
    mocker.patch('foo.Foo.bar', return_value="y", new_callable=mocker.PropertyMock)
    f = foo.Foo()
    assert f.bar == "y"

This made the test work.

Cristiano Araujo
  • 1,632
  • 2
  • 21
  • 32