0

I am writing UT for one of my function where I have to patch 2 objects.

@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 = {}

This gives error:

----------------------------------------------------------------------
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 << ----------------------

When I am accessing second argument, means mock_gridfs why it return Mock object for MongoClient?

Nilesh
  • 20,521
  • 16
  • 92
  • 148

1 Answers1

1

You have them in the wrong order, put the params in the reverse order you define them.

@patch('mypackage.models.db_models.MongoClient',
       return_value={})
@patch('mypackage.models.db_models.GridFS')
def test_file_in_db(self, mock_gridfs, mock_mongoclient):
Dan
  • 1,874
  • 1
  • 16
  • 21