How to Use pytest with Flask for Testing Flask Apps
To use
pytest with Flask, create a test client from your Flask app using app.test_client() inside a test function. Then write test functions that use this client to simulate requests and check responses. Run tests by executing pytest in your project directory.Syntax
Use app.test_client() to create a client that simulates requests to your Flask app. Write test functions starting with test_ that use this client to send HTTP requests like get or post. Use assert statements to check the response status and data.
python
def test_example(): with app.test_client() as client: response = client.get('/') assert response.status_code == 200 assert b'Hello' in response.data
Example
This example shows a simple Flask app and a pytest test that checks the home page returns status 200 and contains the word 'Hello'.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Hello, Flask!' def test_home(): with app.test_client() as client: response = client.get('/') assert response.status_code == 200 assert b'Hello' in response.data if __name__ == '__main__': app.run()
Output
============================= test session starts ==============================
collected 1 item
test_app.py . [100%]
============================== 1 passed in 0.03s ===============================
Common Pitfalls
- Not using
with app.test_client()context can cause issues with request context. - Forgetting to check
response.status_codemay miss failed requests. - Using
response.dataas a string instead of bytes can cause assertion errors. - Not installing
pytestor running tests outside the project folder.
python
def test_wrong(): client = app.test_client() response = client.get('/') assert response.status_code == 404 # Wrong status expected def test_right(): with app.test_client() as client: response = client.get('/') assert response.status_code == 200 # Correct status check
Quick Reference
- Create test client:
with app.test_client() as client: - Send request:
client.get('/path')orclient.post('/path', data={}) - Check response:
assert response.status_code == 200,assert b'text' in response.data - Run tests: Run
pytestin terminal
Key Takeaways
Use app.test_client() inside a with-block to simulate requests in pytest.
Write test functions starting with test_ that send requests and assert responses.
Always check response.status_code and response.data in your tests.
Run your tests by simply running pytest in your project folder.
Avoid common mistakes like missing the with-block or wrong assertions.