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
- Create an
appfixture and push its context for tests that need it. - Use the app/test client fixture in the tests that touch app-bound code.
- Re-run.
conftest.py
import pytest
from myapp import create_app
@pytest.fixture
def app():
app = create_app("testing")
with app.app_context():
yield appDefer 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 contextHow to prevent it
- Provide an
appfixture 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
Django "ImproperlyConfigured: settings are not configured" in CIFix Django "ImproperlyConfigured: Requested setting X, but settings are not configured" in CI - DJANGO_SETTIN…
pytest "fixture 'db' not found" (pytest-django) in CIFix pytest "fixture 'db' not found" in CI - the pytest-django plugin is not installed or not active, so its d…
pytest "ImportError" from conftest at the wrong level in CIFix a pytest "ImportError while loading conftest" caused by a conftest.py at the wrong directory level in CI…