5

我在测试我的 Flask 应用程序时遇到了一点问题。我的观点是这样的:

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

我的测试功能是这样的:

@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/prelogin?email=someone@example.com')
    self.assert_status(response, 200)

如果我尝试在测试函数中打印模拟对象,它们会返回正确的值。然而,鉴于我仍然得到:

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变量返回为<MagicMock name='pymongo.db.photos.find_one()' id='59485392'>.

我是否使用模拟不好的方式,修补错误的地方?

4

1 回答 1

4

mock_usermock_pymongo论点的顺序错误;最外层的@patch(第一个/最远离方法)是最后一个方法参数。它应该是

@patch('arounded.userv2.views.User')
@patch('arounded.userv2.views.pymongo')
def test_valid_prelogin(self, mock_pymongo, mock_user):
于 2013-06-04T09:43:18.310 回答