0
0
Flaskframework~5 mins

Test fixtures with pytest in Flask

Choose your learning style9 modes available
Introduction

Test fixtures help set up the environment for tests so they run smoothly and reliably. They prepare things like data or app states before tests start.

When you need to create a fresh Flask app instance for each test.
When you want to set up a test database before running tests.
When you need to prepare some data or configuration used by multiple tests.
When you want to clean up resources after tests finish.
When you want to avoid repeating setup code in every test function.
Syntax
Flask
import pytest

@pytest.fixture
def fixture_name():
    # setup code
    yield resource
    # teardown code

Use @pytest.fixture to mark a function as a fixture.

The yield keyword splits setup (before yield) and teardown (after yield).

Examples
This fixture creates and provides a Flask app instance for tests.
Flask
import pytest

@pytest.fixture
def app():
    from myapp import create_app
    app = create_app()
    yield app
This fixture uses the app fixture to create a test client for HTTP requests.
Flask
import pytest

@pytest.fixture
def client(app):
    return app.test_client()
This fixture provides sample data for tests.
Flask
import pytest

@pytest.fixture
def sample_data():
    data = {'name': 'Alice', 'age': 30}
    yield data
    # no teardown needed here
Sample Program

This example shows two fixtures: app creates a Flask app, and client creates a test client. The test test_hello uses the client to call the '/hello' route and checks the response.

Flask
import pytest
from flask import Flask, jsonify

@pytest.fixture
def app():
    app = Flask(__name__)

    @app.route('/hello')
    def hello():
        return jsonify(message='Hello, world!')

    yield app

@pytest.fixture
def client(app):
    return app.test_client()


def test_hello(client):
    response = client.get('/hello')
    assert response.status_code == 200
    assert response.json == {'message': 'Hello, world!'}
OutputSuccess
Important Notes

Fixtures can depend on other fixtures by listing them as parameters.

Use fixtures to keep tests clean and avoid repeating setup code.

Teardown code after yield runs after the test finishes, useful for cleanup.

Summary

Fixtures prepare and clean up test environments automatically.

Use @pytest.fixture to create reusable setup code.

Fixtures can provide Flask app instances, test clients, or test data.