Skip to content
Latchkey

Flask "RuntimeError: Working outside of application context" in CI

Flask exposes current_app, g, and extensions only while an application context is pushed. A test that calls into app-bound code without pushing one (or after it popped) raises this RuntimeError.

What this error means

A pytest test fails with "RuntimeError: Working outside of application context." It often passes when run through the app server but fails in isolated unit tests.

pytest
RuntimeError: Working outside of application context.

This typically means that you attempted to use functionality that needed
the current application. To solve this, set up an application context
with app.app_context().

Common causes

No app context pushed in the test

Accessing current_app, g, or db.session requires an active app context; a plain unit test has none.

Module-level app-bound code at import time

Code that touches the app context at import (before any context exists) fails during collection.

How to fix it

Push an app context in a fixture

  1. Create an app fixture and push its context for tests that need it.
  2. Use the app/test client fixture in the tests that touch app-bound code.
  3. Re-run.
conftest.py
import pytest
from myapp import create_app

@pytest.fixture
def app():
    app = create_app("testing")
    with app.app_context():
        yield app

Defer app-bound access out of import time

Move current_app/g access into functions called within a request or app context, not at module top level.

Python
def get_setting():
    from flask import current_app
    return current_app.config["SETTING"]   # called within a context

How to prevent it

  • Provide an app fixture that pushes the context for tests that need it.
  • Keep app-bound access inside request/app-context scopes, not import time.
  • Use the Flask test client fixture for endpoint tests.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →