Flask-Testing

0.8.1 · active · verified Sun Apr 12

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.

Warnings

Install

Imports

Quickstart

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())

view raw JSON →