Python Unitest模拟一个对象没有属性

发布于 2025-02-12 15:31:45 字数 395 浏览 1 评论 0原文

如果对象具有某个属性,则我的函数可以运行一些代码,在极少数情况下,如果对象没有属性,则运行不同的代码。我很难在没有测试属性的情况下创建对象。我尝试了del instance.attribute,但出现了错误。该属性实际上是引擎盖下方的@property

我有一个具有foo属性的对象实例。一个人如何模拟它,以便当一个人尝试访问instance.foo时,如果没有属性,它会像往常一样添加attributeError

我尝试了mock.mock(side_effect = attributeError('boom!')),但它仅适用于方法。

I have a function that runs some code if the object has a certain attribute, and in rare cases if if the object does not have the attribute, it runs different code. It is hard for me to create the object without the attribute for testing. I tried del instance.attribute but got an error. The attribute is actually a @property under the hood.

I have an object instance that has foo attribute. How does one mock it so that when one tries to access instance.foo it raises an AttributeError as usual if there is no attribute?

I tried mock.Mock(side_effect=AttributeError('Boom!')) but it only works with methods.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天冷不及心凉 2025-02-19 15:31:45

您可以尝试使用属性,通常您可以设置各自的副作用。这是一个简单的工作示例:

from unittest import mock
import pytest

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


def test_no_foo():
    bar_mock = mock.PropertyMock()
    with mock.patch(f"{__name__}.Foo.bar", bar_mock):
        bar_mock.side_effect = AttributeError('Boom!')
        foo = Foo()
        with pytest.raises(AttributeError):
            foo.bar

当您修补类中的属性而不是对象中的属性时,您也可以使用patch.Object进行此操作,如果您可以通过访问对象访问对象的访问对象:

def test_no_foo():
    bar_mock = mock.PropertyMock()
    foo = Foo()
    with mock.patch.object(foo.__class__, "bar", bar_mock):
        bar_mock.side_effect = AttributeError('Boom!')
        with pytest.raises(AttributeError):
            foo.bar

You could try to use a PropertyMock for the property, and generally you shall be able to set the respective side effect. Here is a simple working example:

from unittest import mock
import pytest

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


def test_no_foo():
    bar_mock = mock.PropertyMock()
    with mock.patch(f"{__name__}.Foo.bar", bar_mock):
        bar_mock.side_effect = AttributeError('Boom!')
        foo = Foo()
        with pytest.raises(AttributeError):
            foo.bar

As you patch the property in the class, not in the object, you can can also do this using patch.object if you have access to the object by accessing the class of the object:

def test_no_foo():
    bar_mock = mock.PropertyMock()
    foo = Foo()
    with mock.patch.object(foo.__class__, "bar", bar_mock):
        bar_mock.side_effect = AttributeError('Boom!')
        with pytest.raises(AttributeError):
            foo.bar
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文