I want to test the input/output for a POST request with flask, and possibly mock both outcomes if possible. For simplicity, I've stripped down most of the logic.
# extract.py
import app # This is the main flask app. Just a basic setup.
from flask import jsonify, request
@app.route('/extract', methods=['POST'])
def task():
args = request.json
table_name = args.get('table')
start_date = args.get('start_date')
end_date = args.get('end_date')
# Logic here
result = dict(key1=value1, key2=value2)
return jsonify(result)
I'm not happy with this scenario, given that everything is mocked and I can't guarantee the function will run properly. Ideally, I'd be able to pass the JSON data for the POST request, and check the response provided by the jsonify(result)
method of extract.py
.
# test_extract.py
# mocker comes from pytest-mock
def test_trigger_extract_1(mocker):
import extract
mocker.patch.object(extract, 'task')
data = [{
'table': 'name',
'start_date': '2020-01-02',
'end_date': '2020-01-03',
}]
extract.task.return_value.status_code = 200
extract.task.return_value.json.return_value = data
extract.task()
extract.task.assert_called_once()
The usual way I'd do this, would be to call request.get('/extract', json=json.dumps(data))
and test against the response provided, given this would actually run the code. The thing is, I know this isn't ideal, because if the server breaks, or something else goes wrong, I won't be able to test it properly.