XD blog

blog page

flask, python, unit test


2014-12-21 Unit test a Flask application

It is usually quite annoying to develop a web application and to test the code by just running it and checking it produces what you expect for a given request. It would be more simple to write a function which launches the web application on a local machine and retrieves the content of a given page. That describes what a unit test could be used for.

I used Flask to do it. I hesitated to choose bottle but I needed to be able to shutdown the application by some means. I found a way for Flask faster than for Bottle. That's why I used the first one.

The code the wep application can be found here: simple_flask_site.py. The first trick is to be able to shutdown the service:

def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown/', methods=['POST'])
def shutdown():
    shutdown_server()
    return Text2Response('Server shutting down...')

And you do it with:

import requests
c = requests.post( "http://localhost:8025/shutdown/")

The second trick is after the web application has started, another thread must continue to query the website. So we run the website within a thread:

from ensae_teaching_cs.td_1a.simple_flask_site import app
th = FlaskInThread(app, host="localhost", port=8025)
th.start()  # just run app.run
# ... any kind of test
requests.post( "http://localhost:8025/shutdown/")

<-- -->

Xavier Dupré