【问题标题】:How can I mock a property to raise an exception?如何模拟属性以引发异常?
【发布时间】:2023-03-27 17:41:01
【问题描述】:

我在 Python 2.7 中使用 MagicMock 来模拟对象。我正在模拟的其中一个类具有属性,其中一个在某些情况下可以引发 TypeError

我想模拟这种行为,但我不知道如何:

  • 如果访问my_propertydel my_mock.my_property 将导致AttributeError,但我需要TypeError
  • my_property调用时,my_mock.my_property = MagicMock(side_effect=TypeError) 会导致TypeError,但在仅被访问时不会。

我该怎么做?

【问题讨论】:

  • 只是一个想法:第二个选项 + my_mock.my_property = property(my_mock.my_property)
  • 也许让属性成为一个定义__delattr__方法的类,该方法在删除时会改变其行为。
  • 我们也许更准确地说,为 mock 对象定义一个 __delattr__ 方法,该方法将在删除时更改属性的行为。
  • 我们将属性设为descriptor,在删除时会执行类似的操作。

标签: python python-2.7 unit-testing mocking magicmock


【解决方案1】:

您可以为此使用PropertyMock

import mock

class A(object):

    @property
    def prop(self):
        pass

a = A()
type(a).prop = mock.PropertyMock(side_effect=TypeError)

如果您现在访问a.prop,它将引发TypeError

【讨论】:

  • 这看起来像我需要的,我会在星期一检查。我也可以在 MagicMock 实例上设置它吗?
  • 这很好,除非您想使用自定义消息side_effect=AttributeError('something') 引发 AttributeError。那么 side_effect 就被完全忽略了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-07
  • 1970-01-01
  • 2019-07-31
  • 2015-03-08
  • 2014-02-15
  • 2015-04-03
  • 2017-04-05
相关资源
最近更新 更多