Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking pymongo in Flask

I've got little problem with testing my Flask app. My view looks like this:

def prelogin():
    email = request.args.get('email')
    if not email:
        return '', 204
    user = User.query.filter({'email': email}).first()
    if not user:
        return '', 204
    address = current_app.config['UPLOADED_PHOTOS_URL']
    try:
        mongo_photo = pymongo.db.photos.find_one(user.photo)
        photo = address + mongo_photo['file']
    except (KeyError, AttributeError):
        photo = None
    return jsonify({
        'email': email,
        'fullname': user.fullname,
        'photo': photo
    })

and my test function like this:

@patch('arounded.userv2.views.User')
@patch('arounded.userv2.views.pymongo')
def test_valid_prelogin(self, mock_user, mock_pymongo):
    user_config = {
        'filter.return_value.first.return_value.fullname': 'Someone'
    }
    mock_user.query.configure_mock(**user_config)
    mock_pymongo.db.photos.find_one.return_value = {'file': 'no-photo.png'}
    response = self.client.get(
        '/api/v2/users/[email protected]')
    self.assert_status(response, 200)

If I try to print mock objects in test function, they return correct values. Yet in view I'm still getting:

arounded/userv2/views.py line 40 in prelogin
  'photo': photo
/home/sputnikus/.virtualenvs/arounded_site2/lib/python2.7/site-packages/flask_jsonpify.py line 60 in jsonpify
  indent=None if request.is_xhr else 2)),
/usr/lib64/python2.7/json/__init__.py line 250 in dumps
  sort_keys=sort_keys, **kw).encode(obj)
/usr/lib64/python2.7/json/encoder.py line 209 in encode
  chunks = list(chunks)
/usr/lib64/python2.7/json/encoder.py line 434 in _iterencode
  for chunk in _iterencode_dict(o, _current_indent_level):
/usr/lib64/python2.7/json/encoder.py line 408 in _iterencode_dict
  for chunk in chunks:
/usr/lib64/python2.7/json/encoder.py line 442 in _iterencode
  o = _default(o)
/usr/lib64/python2.7/json/encoder.py line 184 in default
  raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <MagicMock name='pymongo.db.photos.find_one().__getitem__().__radd__()' id='67038032'> is not JSON serializable

mongo_photo variable is returned as <MagicMock name='pymongo.db.photos.find_one()' id='59485392'>.

Do I use mock bad way, patching on wrong place?

like image 337
sputnikus Avatar asked Oct 03 '22 23:10

sputnikus


1 Answers

Your mock_user and mock_pymongo arguments are in wrong order; the outermost @patch (first/furthest away from the method) is the last method argument. It should be

@patch('arounded.userv2.views.User')
@patch('arounded.userv2.views.pymongo')
def test_valid_prelogin(self, mock_pymongo, mock_user):
like image 139
Tommi Komulainen Avatar answered Oct 07 '22 18:10

Tommi Komulainen