pytest-flask
01 / 02

pytest-flask: Database State, Mocking & Auth Testing

pytest-flask: Database State, Mocking & Auth Testing

Isolated Test Database

A dedicated test database (often in-memory SQLite) avoids polluting real development/production data and gives each test run a clean, predictable starting state.

Resetting State Between Tests

@pytest.fixture
def db_session(app):
    with app.app_context():
        db.create_all()
        yield db.session
        db.session.rollback()
        db.drop_all()

# Each test starts from a clean slate -- no leftover state
# from a previous test affecting the next one's assumptions

Mocking External Dependencies

Mocking an external API call (rather than making a real network request) keeps tests fast, reliable, and independent of that service's actual availability at test-run time.

Testing Authentication & Redirects

def test_requires_auth(client):
    response = client.get("/profile")
    assert response.status_code == 401

def test_login_redirect(client):
    response = client.post("/login", data={...})
    assert response.status_code == 302
    assert response.headers["Location"] == "/dashboard"

Parametrized Input Testing

@pytest.mark.parametrize lets a single test function run against a list of different input values -- concisely covering valid input, missing fields, and invalid types without copy-pasting near-identical test functions.

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free