【问题标题】:Python unittest mock: mocking a class function via a parameterized class object?Python unittest mock:通过参数化的类对象模拟类函数?
【发布时间】:2016-01-26 00:31:18
【问题描述】:

lib/thing.py:

class Class(object):
    def class_function1(self):

app/thing.py:

def function2(class_object):
    class_object.class_function1()

test/test_thing.py 中,我想在使用模拟的 Class() 对象调用 function2 时修补lib.thing.Class.class_function1 以引发AttributeError,该AttributeError 应该可以畅通无阻地提高到test_function2。像这样的东西(不起作用):

def test_function2(self):
    mocked_class = mock.MagicMock(name="class", spec_set=lib.thing.Class)
    with assertRaises(AttributeError):
        with patch ('lib.thing.Class.class_function1', side_effect=AttributeError):
            function2(mocked_class)

【问题讨论】:

  • 删除补丁并仅设置mocked_class.class_function1.side_effect = AttributeError 会在class_function1function2 命中时正确提高AttributeError,但assertRaises 不承认它。嗯。靠近一步或侧身一步......

标签: mocking python-unittest magicmock


【解决方案1】:

我完全放弃了补丁,并在模拟的类对象中使用了 side_effect。

def test_function2(class_object):
    mocked_class = mock.MagicMock(name="class", spec_set=lib.thing.Class)
    mocked_class.class_function1.side_effect = AttributeError("sorry for the pseudo code")
    with assertRaises(AttributeError):
         function2(mocked_class)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多