dimanche 19 juin 2016

Mocking info() from redis-py, but response from Flask has errors

I'm trying to learn how to use the Mock library in python.

I have a Flask application which is connected to Redis via redis-py package.

In the '/myapp/version' API of my app, I call a info() from redis-py, and format a HTTP response back where the JSON data includes also the return data from the info() call:

from Flask import Flask, jsonify
from Redis import StricRedis

app = Flask(__name__)
redis = StrictRedis(host='redis', port=6379)

@app.route('/myapp/version', methods=['GET'])
def get_version():
    redis_info = redis.info() //returns a dict
    return jsonify({
        'app_version': '0.1',
        'flask_version': '0.11.1',
        'redis_info': redis_info
    })

And this is my test.py, which uses the Flask test_client:

import json
import mock
import redis
import myapp import app

class TestApp:
    @classmethod
    def setup_class(self):
        self.client = app.test_client()
        self.client.testing = True

   @mock.patch.object(redis.StrictRedis, 'info')
    def test_get_version(self, mock_info):
        self.client.get('/acrewstic/version')
        # assert result.status_code == 200
        mock_info.assert_called()

If I launch nosetests, the test will pass but only because I don't assert the status code of the response. The response in badly formatted. The problem is that the info() call is correctly mocked, but then it cannot be serialzed to JSON to format the response by the Flask test client, so if I run the test I get the following trackback:

TypeError: <MagicMock name='info()' id='140548379595472'> is not JSON serializable

Am I using Mock in the wrong way? I know it is handy in unit test but here it'm more like integration testing. Is there a way to get a valid response anyway?

Aucun commentaire:

Enregistrer un commentaire