Pytest on Flask: Setting up the Flask App for Testing

Get to know how to prepare a Flask application for testing.

Pytest on Flask

Testing Flask applications with pytest is trickier than testing the basic logic, because we can’t just call the application methods and have it work. A Flask application instance needs to be created first. There’s also the database to worry about. We need the server to access the database, but we also need to be sure we don’t mess up the real data. Generally, a separate testing database will make this possible. We’ll use pytest fixtures to handle both the Flask application instance and, in the next chapter, the testing database.

Application context

To test the application, we need to give it an application context. In Flask, a context is everything an application would normally have when responding to HTTP requests. The tests can then make those requests and analyze the responses. Here’s what a simple Flask application fixture looks like:

Get hands-on with 1200+ tech skills courses.