title: Mocking pymongo in Flask
body: <p>I've got little problem with testing my Flask app. My view looks like this:</p>
  
  <pre><code>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
      })
  </code></pre>
  
  <p>and my test function like this:</p>
  
  <pre><code>@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)
  </code></pre>
  
  <p>If I try to print mock objects in test function, they return correct values. Yet in view I'm still getting:</p>
  
  <pre><code>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: &lt;MagicMock name='pymongo.db.photos.find_one().__getitem__().__radd__()' id='67038032'&gt; is not JSON serializable
  </code></pre>
  
  <p><code>mongo_photo</code> variable is returned as <code>&lt;MagicMock name='pymongo.db.photos.find_one()' id='59485392'&gt;</code>.</p>
  
  <p>Do I use mock bad way, patching on wrong place?</p>