This example assumes you know how to test a Flask app using pytest
Below is an API that takes a JSON input with integer values a
and b
e.g. {"a": 1, "b": 2}
, adds them up and returns sum a + b
in a JSON response e.g. {"sum": 3}
.
# hello_add.py
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/add', methods=['POST'])
def add():
data = request.get_json()
return jsonify({'sum': data['a'] + data['b']})
pytest
We can test it with pytest
# test_hello_add.py
from hello_add import app
from flask import json
def test_add():
response = app.test_client().post(
'/add',
data=json.dumps({'a': 1, 'b': 2}),
content_type='application/json',
)
data = json.loads(response.get_data(as_text=True))
assert response.status_code == 200
assert data['sum'] == 3
Now run the test with py.test
command.