Registry / testing / flask-testing

flask-testing

JSON →
library0.8.1pypypi✓ verified 23d ago

Flask-Testing is a stable Python library designed to provide unit testing utilities for Flask applications. It integrates seamlessly with Python's built-in `unittest` module, offering `TestCase` and `LiveServerTestCase` classes that simplify testing Flask components, including routes, templates, and live server interactions. Currently at version 0.8.1, the library maintains a moderate release cadence, focusing on stability and compatibility with Flask's ecosystem.

pip install flask-testing
INSTALL
IMPORT
SIG · FLASK-TESTING
F
flask-testing
testingpythonv0.8.1
Install
3.1s avg
Import
573ms
Disk
22MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v0.8.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.584s · 23.9MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 3.1s · import 0.562s · 24MB
22MB installed
● package 22MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

TestCase
from flask_testing import TestCase
from flask.ext.testing import TestCase
The `flask.ext.testing` import path was deprecated in Flask-Testing v0.4.0 and should no longer be used.
LiveServerTestCase
from flask_testing import LiveServerTestCase
from flask.ext.testing import LiveServerTestCase
The `flask.ext.testing` import path was deprecated in Flask-Testing v0.4.0 and should no longer be used.

This quickstart demonstrates basic usage of `TestCase` for unit tests with Flask's test client, and `LiveServerTestCase` for tests requiring a running server, such as integration with browser automation tools. Ensure your Flask app is properly configured for testing and the `create_app` method is implemented in your test classes. Using `LIVESERVER_PORT = 0` allows the operating system to dynamically assign an available port, which is useful for parallel test execution.

import os from flask import Flask, jsonify from flask_testing import TestCase, LiveServerTestCase # A simple Flask application to test def create_test_app(): app = Flask(__name__) app.config['TESTING'] = True app.config['SECRET_KEY'] = os.environ.get('FLASK_SECRET_KEY', 'default_secret_key') @app.route('/') def index(): return 'Hello Flask-Testing!' @app.route('/data') def get_data(): return jsonify({'message': 'Data retrieved!'}) return app class MyUnitTests(TestCase): def create_app(self): return create_test_app() def test_index_page(self): response = self.client.get('/') self.assert200(response) self.assertIn(b'Hello Flask-Testing!', response.data) def test_json_data(self): response = self.client.get('/data') self.assert200(response) self.assertContentType('application/json', response) self.assertEqual(response.json, {'message': 'Data retrieved!'}) class MyLiveServerTests(LiveServerTestCase): def create_app(self): app = create_test_app() app.config['LIVESERVER_PORT'] = 0 # Let OS pick an available port return app def test_server_running_and_accessible(self): import urllib.request response = urllib.request.urlopen(self.get_server_url()) self.assertEqual(response.code, 200) self.assertIn(b'Hello Flask-Testing!', response.read())
Debug
Known issues
breakingFlask-Testing v0.8.0 dropped official support for Python 2.6, 3.3, and 3.4. Users on these older Python versions should use an earlier Flask-Testing version or upgrade their Python environment.
fix
Upgrade to Python 3.5+ or pin `flask-testing<0.8.0`.
affects: >=0.8.0
breakingVersions of Flask-Testing prior to v0.8.0 may have compatibility issues with Werkzeug 1.0 due to changes in import paths within Werkzeug.
fix
Upgrade Flask-Testing to v0.8.0 or newer to ensure compatibility with Werkzeug 1.0+.
affects: <0.8.0
deprecatedThe import path `from flask.ext.testing import ...` is deprecated. The correct modern import path is `from flask_testing import ...`.
fix
Update your import statements to use `from flask_testing import TestCase` or `from flask_testing import LiveServerTestCase`.
affects: All versions since v0.4.0
gotchaSubclasses of `TestCase` and `LiveServerTestCase` *must* implement a `create_app` method that returns a Flask application instance. Failure to do so will result in a `NotImplementedError`.
fix
Define `def create_app(self):` in your test class and return your configured Flask app from it.
affects: All versions
gotchaFor features like `assertTemplateUsed` and `get_context_variable`, the `blinker` library must be installed. Without it, these methods might not function correctly or prevent tests from running.
fix
Install `blinker` if you plan to use features that rely on Flask's signals: `pip install blinker`.
affects: All versions
gotchaWhen using `LiveServerTestCase` for parallel testing, explicitly set `app.config['LIVESERVER_PORT'] = 0` within your `create_app` method to allow the operating system to dynamically assign an available port. Otherwise, tests might conflict over the default port (5000).
fix
Add `app.config['LIVESERVER_PORT'] = 0` to your `create_app` method in `LiveServerTestCase` subclasses.
affects: All versions
Errors
Common errors & fixes
AttributeError: 'FlaskClientTestCase' object has no attribute 'app_context'
This error often occurs when the `setUp` method in your test class is incorrectly named `setup` (lowercase 'u'). Python's `unittest` module, which Flask-Testing extends, requires the method to be `setUp` (camel case) to be recognized and run before each test, preventing the proper initialization of attributes like `app_context` or `client`.
fix
Ensure your test setup method is correctly spelled `setUp` (with an uppercase 'U').

```python
from flask_testing import TestCase
from my_app import create_app # Assuming you have an app factory

class MyTests(TestCase):
    def create_app(self):
        app = create_app()
        app.config['TESTING'] = True
        return app

    def setUp(self): # Correct spelling
        pass # Your setup code here

    def test_something(self):
        # Your test code here, self.app and self.client will be available
        response = self.client.get('/')
        self.assert200(response)
```
AttributeError: 'Flask' object has no attribute 'get' (or 'post', 'put', etc.)
This error happens when you attempt to call HTTP request methods (like `get`, `post`) directly on the Flask application object (`self.app`) instead of on the test client instance (`self.client`). The `TestCase` in Flask-Testing provides a `self.client` attribute for making requests.
fix
Always use `self.client` to make HTTP requests in your tests, not `self.app`.

```python
from flask_testing import TestCase
from my_app import create_app

class MyTests(TestCase):
    def create_app(self):
        app = create_app()
        app.config['TESTING'] = True
        return app

    def test_homepage(self):
        # Incorrect: response = self.app.get('/')
        response = self.client.get('/') # Correct
        self.assert200(response)
```
ModuleNotFoundError: No module named 'flask.json.tag'
This specific `ModuleNotFoundError` typically indicates a compatibility issue between your Flask version (specifically Flask 1.0 and later) and an older version of Werkzeug (less than 0.15). Flask 1.0 moved some internal modules, and older Werkzeug versions might expect them in a different location.
fix
Upgrade your Flask and Werkzeug libraries to compatible versions. This often means ensuring both Flask and Werkzeug are up-to-date or that your Flask version is compatible with your Werkzeug version (e.g., Flask 1.0+ requires Werkzeug 0.15+). A common fix is to upgrade Flask, which usually brings in a compatible Werkzeug version.

```bash
pip install --upgrade Flask Werkzeug
```
Upgrade
Version history
0.8.1latest on PyPI · released Dec 24, 2020
Audit
Dependencies
FlaskrequiredCore dependency as Flask-Testing is an extension for Flask applications.
BlinkeroptionalRequired for `assertTemplateUsed` and `get_context_variable` functionality, which relies on Flask's signals. (Optional for basic usage)
Agent activity
5 hits · last 30 days
node
4
Resources
flask-testing — pip install flask-testing · libregistry