如何在 pytest 中使用 mocker 修补属性

Cri*_*ujo 4 python pytest pytest-mock

我有一个项目需要使用mocker夹具来模拟属性。它使用 pytest 和 pytest-mock:

pip install pytest pytest-mock
Run Code Online (Sandbox Code Playgroud)

问题的一个简单例子:

foofoo.py文件中有该类:

class Foo:
    @property
    def bar(self):
        return "x"
Run Code Online (Sandbox Code Playgroud)

我必须测试它模拟该属性bar

pip install pytest pytest-mock
Run Code Online (Sandbox Code Playgroud)

但是当我修补它时,该栏的行为就像可调用的而不像属性,如何解决这个问题?

Cri*_*ujo 6

我能够使用mocker.PropertyMock@idjaw 评论。

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"
Run Code Online (Sandbox Code Playgroud)

这使得测试成功。