0
# pytest-flask
1
2
A pytest plugin that provides a comprehensive set of fixtures and utilities for testing Flask web applications. This plugin extends pytest's testing capabilities with Flask-specific fixtures including test client creation, live server functionality, request context management, and specialized assertion helpers.
3
4
## Package Information
5
6
- **Package Name**: pytest-flask
7
- **Package Type**: pytest plugin
8
- **Language**: Python
9
- **Installation**: `pip install pytest-flask`
10
11
## Core Imports
12
13
The plugin automatically registers itself with pytest through the `pytest11` entry point defined in setup.cfg. No manual imports are required in test files - just install the package and the fixtures become available.
14
15
**Entry Point Registration (setup.cfg):**
16
```ini
17
[options.entry_points]
18
pytest11 =
19
flask = pytest_flask.plugin
20
```
21
22
This registration makes all fixtures available automatically when pytest runs. The plugin also registers custom pytest markers and command line options through plugin hooks:
23
24
**Registered Markers:**
25
- `@pytest.mark.app(options)` - pass options to your application factory
26
- `@pytest.mark.options` - app config manipulation
27
28
**Command Line Options Added:**
29
- `--start-live-server` / `--no-start-live-server` - control automatic server startup
30
- `--live-server-wait` - set server startup timeout
31
- `--live-server-clean-stop` / `--no-live-server-clean-stop` - control shutdown behavior
32
- `--live-server-host` / `--live-server-port` - configure server address
33
34
For application factory pattern:
35
36
```python
37
import pytest
38
from myapp import create_app
39
40
@pytest.fixture
41
def app():
42
app = create_app()
43
app.config['TESTING'] = True
44
return app
45
```
46
47
## Basic Usage
48
49
```python
50
import pytest
51
from flask import url_for, jsonify
52
from myapp import create_app
53
54
@pytest.fixture
55
def app():
56
"""Application factory fixture - required by pytest-flask"""
57
app = create_app()
58
app.config['TESTING'] = True
59
app.config['SECRET_KEY'] = 'test-secret'
60
61
# Simple test route
62
@app.route('/ping')
63
def ping():
64
return jsonify(ping='pong')
65
66
return app
67
68
def test_ping_endpoint(client):
69
"""Test using the test client fixture"""
70
response = client.get(url_for('ping'))
71
assert response.status_code == 200
72
assert response.json == {'ping': 'pong'}
73
74
def test_with_live_server(live_server):
75
"""Test using the live server fixture"""
76
import requests
77
response = requests.get(live_server.url('/ping'))
78
assert response.status_code == 200
79
assert response.json() == {'ping': 'pong'}
80
81
@pytest.mark.options(debug=True, testing=False)
82
def test_with_custom_config(app, config):
83
"""Test using configuration markers and fixtures"""
84
assert app.debug is True
85
assert config['TESTING'] is False
86
```
87
88
## Architecture
89
90
pytest-flask provides testing infrastructure through three main layers:
91
92
- **Plugin Integration**: Registers with pytest via entry points, providing automatic fixture loading
93
- **Fixture System**: Core fixtures (client, config, live_server) with automatic Flask app detection
94
- **Enhanced Testing**: JSON response helpers, request context management, and configuration markers
95
96
The plugin requires users to define an `app` fixture that returns a Flask application instance, then automatically provides dependent fixtures for comprehensive Flask application testing.
97
98
## Capabilities
99
100
### Test Client Fixtures
101
102
Provides Flask test client instances and utilities for HTTP request testing. Includes standard test client access and class-based test integration.
103
104
```python { .api }
105
@pytest.fixture
106
def client(app): ...
107
108
@pytest.fixture
109
def client_class(request, client): ...
110
```
111
112
[Test Client](./test-client.md)
113
114
### Application Configuration
115
116
Access and manipulation of Flask application configuration during tests, including runtime config changes via markers.
117
118
```python { .api }
119
@pytest.fixture
120
def config(app): ...
121
122
# Marker usage
123
@pytest.mark.options(debug=True, testing=False)
124
def test_function(): ...
125
```
126
127
[Configuration](./configuration.md)
128
129
### Live Server Testing
130
131
Runs Flask applications in separate processes for integration testing with real HTTP requests and external service interaction.
132
133
```python { .api }
134
@pytest.fixture(scope=_determine_scope)
135
def live_server(request, app, pytestconfig): ...
136
137
class LiveServer:
138
def start(self): ...
139
def stop(self): ...
140
def url(self, url=""): ...
141
```
142
143
[Live Server](./live-server.md)
144
145
### HTTP Accept Headers
146
147
Pre-configured accept header fixtures for testing content negotiation and API responses with different MIME types.
148
149
```python { .api }
150
@pytest.fixture
151
def accept_json(request): ...
152
153
@pytest.fixture
154
def accept_jsonp(): ...
155
156
@pytest.fixture(params=["application/json", "text/html"])
157
def accept_mimetype(request): ...
158
159
@pytest.fixture(params=["*", "*/*"])
160
def accept_any(request): ...
161
```
162
163
[Accept Headers](./accept-headers.md)
164
165
### Automatic Test Enhancements
166
167
pytest-flask automatically enhances test responses and provides automatic request context management without requiring explicit setup.
168
169
```python { .api }
170
class JSONResponse:
171
"""
172
Mixin with testing helper methods for JSON responses.
173
Automatically applied to all Flask test responses.
174
"""
175
def __eq__(self, other):
176
"""Allow direct comparison with HTTP status codes"""
177
178
def _push_request_context(request):
179
"""
180
Automatic fixture that pushes Flask request context during tests.
181
Enables url_for, session, and other Flask utilities in tests.
182
"""
183
184
def _configure_application(request, monkeypatch):
185
"""
186
Automatic fixture that applies @pytest.mark.options decorations
187
to Flask application configuration.
188
"""
189
```
190
191
The plugin automatically registers pytest markers and configures test environments, eliminating the need for manual setup in most cases.