修补2个对象时,第二个返回修补后的值

时间:2016-06-22 21:51:16

标签: python mocking patch python-unittest magicmock

我正在为我的一个函数编写UT,我必须修补2个对象。

window.onload

这会出错:

@patch('mypackage.models.db_models.MongoClient',
       return_value={})
@patch('mypackage.models.db_models.GridFS')
def test_file_in_db(self, mock_mongoclient, mock_gridfs):
    print "*"*80
    print mock_gridfs
    print mock_gridfs.return_value
    print "*"*80
    mock_gridfs.return_value.new_file.return_value = {}

当我访问第二个参数时,意味着---------------------------------------------------------------------- Traceback (most recent call last): File "/venv/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched return func(*args, **keywargs) File "/tests/models/test_db_models.py", line 29, in test_file_in_db mock_gridfs.return_value.new_file.return_value = {} AttributeError: 'dict' object has no attribute 'new_file' -------------------- >> begin captured stdout << --------------------- ******************************************************************************** <MagicMock name='MongoClient' id='4385486992'> {} ******************************************************************************** --------------------- >> end captured stdout << ---------------------- 为什么它会为mock_gridfs返回Mock个对象?

1 个答案:

答案 0 :(得分:1)

你的顺序错误,按照你定义它们的相反顺序排列参数。

@patch('mypackage.models.db_models.MongoClient',
       return_value={})
@patch('mypackage.models.db_models.GridFS')
def test_file_in_db(self, mock_gridfs, mock_mongoclient):