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

2024-03-29 01:04:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我为我的一个函数编写UT,其中我必须修补2个对象。你知道吗

@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对象作为MongoClient?你知道吗


Tags: 对象intestnewdbreturnvaluemodels
1条回答
网友
1楼 · 发布于 2024-03-29 01:04:04

如果它们的顺序不对,请按定义它们的相反顺序放置参数。你知道吗

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

相关问题 更多 >