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?
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):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With