【问题标题】:When patching 2 objects, second return first patched value修补 2 个对象时,第二个返回第一个修补值
【发布时间】:2016-06-22 21:51:16
【问题描述】:

我正在为我的一个函数编写 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 为什么它会为MongoClient 返回Mock 对象?

【问题讨论】:

    标签: python mocking patch python-unittest magicmock


    【解决方案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):
    

    【讨论】:

      猜你喜欢
      • 2019-01-09
      • 2020-02-09
      • 2020-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多