Python模拟库没有为'patch'返回正确的模拟对象

时间:2013-06-27 14:10:33

标签: python

我正在尝试让模拟库返回带补丁的特定模拟对象。无论我尝试什么,如果我在'with'子句中实例化一个新对象,我会获得一个通用的Mock对象,而不是我自定义的对象。

这是我的代码,以日志记录为例:

    import logging

    my_mock = Mock()
    my_mock.id = 'i-12341234'

    with patch('logging.PlaceHolder', new=my_mock) as mockobj:
        print mockobj.id          # correctly prints 'i-12341234'

        newobj = logging.PlaceHolder(None)
        print newobj.id           # prints <Mock name='mock().id' id='47607184'>

每次实例化logging.Placeholder的新实例时,如何让mock返回my_mock?

事实证明,继承Mock并使用new_callable工作传递它。由于我花了一些时间试图使版本高于工作,我仍然欣赏和回答。

1 个答案:

答案 0 :(得分:0)

import logging
from mock import Mock, patch

my_mock = Mock()
my_mock.id = 'i-12341234'

with patch('logging.PlaceHolder', new=my_mock) as mockobj:
    mockobj.return_value = mockobj # <-- added this line.
    print mockobj.id
    newobj = logging.PlaceHolder(None)
    print newobj.id

<强>替代

import logging
from mock import Mock, patch

my_mock = Mock()
my_mock.id = 'i-12341234'
my_mock.return_value = my_mock # <---

with patch('logging.PlaceHolder', new=my_mock) as mockobj:
    assert mockobj.id == 'i-12341234'
    newobj = logging.PlaceHolder(None)
    assert newobj.id == 'i-12341234'