Reputation: 373
I have two Python scripts: let's call them program.py and program_utils.py.
program.py looks like this:
from flask import Flask, request, jsonify
import program_utils
app = Flask(__name__)
@app.route('/mypage')
def my_func():
# Do some stuff here and get a URL parameter
my_var = request.args.get('my_var')
# Get JSON object from another function in program_utils
return program_utils.get_json_object(my_var)
get_json_object() in program_utils.py looks like this:
def get_json_object(my_var):
# Do some calls to other methods to create the JSON object using my_var
return json_object
My question is how do I create a unit test for get_json_object in program_utils to ensure that it is returning the object in the correct format? I have tried writing a regular unit test (treating the method as if it returned a string) but was presented with a run time error saying "working outside of application context".
Upvotes: 4
Views: 4703
Reputation: 127190
You use the test client to test Flask views. Create it with app.test_client()
and then use it to simulate requests to your routes. The response only has the raw data, if you want to compare it as JSON you'll need to load it.
c = app.test_client()
rv = c.get('/mypage', query_string={'my_var': 'my_value'})
assert json.loads(rv.get_data()) == expected_data
The Flask docs have a whole section devoted to introducing this. The Werkzeug docs go into more detail.
Upvotes: 6