Python 使用mock修补不存在的属性

Python 使用mock修补不存在的属性,python,unit-testing,testing,mocking,pytest,Python,Unit Testing,Testing,Mocking,Pytest,我正在尝试测试一个上下文管理器,它使用一个类,该类使用一些\uuu getattr\uuuu魔法来解析该类上实际上不存在的几个属性。我遇到了一个问题,mock在尝试修补类时引发了AttributeError 我要修补的对象的简化示例 class MyClass(object): def __getattr__(self, attr): if attr == 'myfunc': return lambda:return None ra

我正在尝试测试一个上下文管理器,它使用一个类,该类使用一些
\uuu getattr\uuuu
魔法来解析该类上实际上不存在的几个属性。我遇到了一个问题,mock在尝试修补类时引发了AttributeError

我要修补的对象的简化示例

class MyClass(object):
    def __getattr__(self, attr):
        if attr == 'myfunc':
            return lambda:return None
        raise AttributeError('error')


class MyContextManager(object):
    def __init__(self):
        super(MyContextManager, self).__init__()
        self.myclass = MyClass()

    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.myclass.myfunc()
测试代码

def test_MyContextManager():
    with patch.object(MyClass, 'myfunc', return_value=None) as mock_obj:
        with MyContextManager():
             pass

    # Do some tests on mock object
以下是我得到的错误:

AttributeError: <class 'MyClass'> does not have the attribute 'myfunc'
我愿意使用mock之外的另一个库来实现这一点。我也在使用pytest。

要在此类测试中使用,您应该使用
create
参数,该参数将强制创建属性(如果不存在)

因此,您的测试应该执行以下操作:

def test_MyContextManager():
    with patch.object(MyClass, 'myfunc', create=True, return_value=None) as mock_obj:
        with MyContextManager():
             pass
def test_MyContextManager():
    with patch.object(MyClass, 'myfunc', create=True, return_value=None) as mock_obj:
        with MyContextManager():
             pass