pytest-flask
pytest-flask is an extension for the pytest test runner, providing a set of useful fixtures and tools to simplify the testing and development of Flask applications and extensions. It is currently at version 1.3.0 and actively maintained, with releases typically tied to Flask and pytest major version updates and bug fixes.
Warnings
- breaking The `request_ctx` fixture was removed in version 1.3.0 due to compatibility changes with Flask 3.0.0. Older versions of pytest-flask using this fixture will be incompatible with Flask 3.0.0+.
- breaking The `live_server.url` method was removed in version 1.2.0. Direct access to the live server URL should use string formatting or `flask.url_for` with `_external=True`.
- breaking Starting from version 1.0.0, the `live_server` fixture became session-scoped by default. This changes its lifecycle from function-scoped, potentially impacting tests expecting a fresh server for each test function.
- breaking Support for Python 2.7 and 3.4 was dropped in version 1.0.0. Ensure your testing environment uses Python 3.5 or newer.
- gotcha Older versions of `pytest-flask` might encounter incompatibilities with newer versions of Werkzeug (e.g., Werkzeug >=3.1). Check release notes and open issues for specific version requirements.
Install
-
pip install pytest-flask
Imports
- app (fixture)
import pytest # @pytest.fixture def app(): ...
- client (fixture)
def test_something(client): ...
- live_server (fixture)
def test_live_server_access(live_server): ...
Quickstart
# myapp.py
from flask import Flask
def create_app():
app = Flask(__name__)
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
# conftest.py
import pytest
from myapp import create_app
@pytest.fixture
def app():
app = create_app()
app.config.update({"TESTING": True}) # Recommended for testing
yield app
@pytest.fixture
def client(app):
return app.test_client()
# test_app.py
def test_hello_world(client):
response = client.get('/hello')
assert response.status_code == 200
assert b'Hello, World!' in response.data