Skip to content

Fix FastAPI/Starlette middleware with positional arguments. #4118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Mar 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions sentry_sdk/integrations/starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -362,13 +362,13 @@ def patch_middlewares():

if not_yet_patched:

def _sentry_middleware_init(self, cls, **options):
# type: (Any, Any, Any) -> None
def _sentry_middleware_init(self, cls, *args, **kwargs):
# type: (Any, Any, Any, Any) -> None
if cls == SentryAsgiMiddleware:
return old_middleware_init(self, cls, **options)
return old_middleware_init(self, cls, *args, **kwargs)

span_enabled_cls = _enable_span_for_middleware(cls)
old_middleware_init(self, span_enabled_cls, **options)
old_middleware_init(self, span_enabled_cls, *args, **kwargs)

if cls == AuthenticationMiddleware:
patch_authentication_middleware(cls)
Expand Down
23 changes: 22 additions & 1 deletion tests/integrations/starlette/test_starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.trustedhost import TrustedHostMiddleware
from starlette.testclient import TestClient

from tests.integrations.conftest import parametrize_test_configurable_status_codes


Expand Down Expand Up @@ -238,6 +237,12 @@ async def do_stuff(message):
await self.app(scope, receive, do_stuff)


class SampleMiddlewareWithArgs(Middleware):
def __init__(self, app, bla=None):
self.app = app
self.bla = bla


class SampleReceiveSendMiddleware:
def __init__(self, app):
self.app = app
Expand Down Expand Up @@ -862,6 +867,22 @@ def test_middleware_partial_receive_send(sentry_init, capture_events):
idx += 1


@pytest.mark.skipif(
STARLETTE_VERSION < (0, 35),
reason="Positional args for middleware have been introduced in Starlette >= 0.35",
)
def test_middleware_positional_args(sentry_init):
sentry_init(
traces_sample_rate=1.0,
integrations=[StarletteIntegration()],
)
_ = starlette_app_factory(middleware=[Middleware(SampleMiddlewareWithArgs, "bla")])

# Only creating the App with an Middleware with args
# should not raise an error
# So as long as test passes, we are good


def test_legacy_setup(
sentry_init,
capture_events,
Expand Down
Loading