python - 如何模拟一个属性

标签 python python-3.x pytest python-unittest python-mock

我在问如何使用 Python 3 在单元测试中模拟类属性。我尝试了以下方法,这对我遵循文档很有意义,但它不起作用:

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)

我已经安装了 pytestpytest_mock 并像这样运行测试:

pytest foo.py

我收到以下错误:

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

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

我的期望是测试运行时没有错误。

最佳答案

属性机制依赖于在对象类上定义的属性。您不能在类的单个实例上创建“类似属性”的方法或属性(为了更好地理解,请阅读 Python 的 descriptor protocol)

因此,您必须将补丁应用到您的类 - 您可以使用 with 语句,以便在测试后正确恢复该类:

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

关于python - 如何模拟一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42704506/

相关文章:

python - Python 中具有无限小点大小的散点图

python - Google Colab 错误 : Failed to get convolution algorithm. 这可能是因为 cuDNN 初始化失败

python - 为 python version=x 启动 ipython qtconsole/notebook 的正确语法是什么

python - 多维形状的 np.zeros 结构

python - 如何在 pytest config [pytest_addoption] 中指定多个选项

javascript - 当用 python (pytest) 编写测试时,有没有办法实现 Nodejs 代码覆盖率?

python - Selenium python 中的日期时间抛出错误

python - 访问嵌套列表元素,深度在运行时已知

xml - 无法在 xml 中找到具有命名空间的元素

python - pytest 装置从外部范围重新定义名称 [pylint]