首页 > 解决方案 > 结合 mock 和 getattr

问题描述

我想制作一个适合我们团队测试的模拟对象。

但是,默认的getattr行为不是我想要的。请参阅下面的示例。

import mock

class A(mock.MagicMock):
    pass

a = A()
print(a.something)  # got a MagicMock without error
print(getattr(a, "something", False))  # False expected, but got a mock object

我试图覆盖__getattr__方法

import mock

class A(mock.MagicMock):
    def __getattr__(self, name):
        try:
            return object.__getattribute__(self, name)
        except:
            return mock.MagicMock.__getattribute__(self, name)

a = A()
print(getattr(a, "something", False))  # got a False value
print(a.something)  # got attribute error

我不允许更改源代码中的“getattr(...)”

编辑:

The test flow may look like this
import mock

class A:
    def foo(self):
        # the "something" may not be initiated, 
        # and I want it to be 1 rather then a mock object
        stat = getattr(self, "something", 1)  
        stat *= 100
        # the client is valid only when a client connected, 
        # I want to mock it because this is a offline test.
        # Since there all many attributes like "client",
        # I don't want to overwrite every one in the MockA class
        self.client.call("done")  
        return stat

class MockA(A, mock.MagicMock):
    pass

def test_foo():
    a = MockA()
    assert a.foo() == 100
    a.something = 4
    assert a.foo() == 400

标签: pythonunit-testingmockinggetattr

解决方案


推荐阅读