如何模拟类层次结构

时间:2014-03-20 18:53:31

标签: python mocking

我想模拟一个类的层次结构。例如:

class Base(object):
    def one(self):
        return 'one'
    def two(self):
        return 'two'

class Derived(Base):
    def three(self):
        return 'three'

定义基本模拟很简单:

from mock import Mock

def BaseMock():
    mock = Mock()
    mock.one.return_value = 'uno'
    mock.two.return_value = 'dos'
    return mock

def DerivedMock():
    mock = BaseMock()
    mock.three.return_value = 'tres'
    return mock

以上作品,但不完整。我想使用Mock参数specname。我可以像往常一样在BaseMock中指定它们,但在DerivedMock中,我必须修改私有Mock属性,这是不好的形式。

是否有正确的方法来模拟完整的specname类的层次结构?

1 个答案:

答案 0 :(得分:1)

要模拟类层次结构,请像往常一样定义基类mock:

from mock import Mock

def BaseMock():
    mock = Mock(spec=Base, name='BaseMock')
    mock.one.return_value = 'uno'
    mock.two.return_value = 'dos'
    return mock

在派生的模拟中,实例化基础模拟和(可憎的)修改与specname相关的模拟私有属性:

def DerivedMock():
    mock = BaseMock()

    # Set Mock private attributes to Derived
    mock._mock_methods.extend(dir(Derived))
    mock._mock_name = 'DerivedMock'
    mock._spec_class = Derived

    mock.three.return_value = 'tres'

    # Defining DerivedMock.four would cause a spec error
    # mock.four.return_value = 'quatro'

    return mock

现在,模拟DerivedMock看起来像Derived类,除了返回值不同:

d = DerivedMock()
assert isinstance(d, Derived)
assert repr(d).startswith("<Mock name='DerivedeMock' spec='Derived'")

assert d.one() == 'uno'
assert d.two() == 'dos'
assert d.three() == 'tres'