diff --git a/CHANGELOG.md b/CHANGELOG.md index f90a02b269..f0da51b620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,52 @@ # Changelog +## 1.8.0 + +### Various fixes & improvements + +- feat(starlette): add Starlette integration (#1441) by @sl0thentr0py + + **Important:** Remove manual usage of `SentryAsgiMiddleware`! This is now done by the Starlette integration. + + Usage: + + ```python + from starlette.applications import Starlette + + from sentry_sdk.integrations.starlette import StarletteIntegration + + sentry_sdk.init( + dsn="...", + integrations=[StarletteIntegration()], + ) + + app = Starlette(debug=True, routes=[...]) + ``` +- feat(fastapi): add FastAPI integration (#829) by @antonpirker + + **Important:** Remove manual usage of `SentryAsgiMiddleware`! This is now done by the FastAPI integration. + + Usage: + + ```python + from fastapi import FastAPI + + from sentry_sdk.integrations.starlette import StarletteIntegration + from sentry_sdk.integrations.fastapi import FastApiIntegration + + sentry_sdk.init( + dsn="...", + integrations=[StarletteIntegration(), FastApiIntegration()], + ) + + app = FastAPI() + ``` + + Yes, you have to add both, the `StarletteIntegration` **AND** the `FastApiIntegration`! +- fix: avoid sending empty Baggage header (#1507) by @intgr +- fix: properly freeze Baggage object (#1508) by @intgr +- docs: fix simple typo, collecter -> collector (#1505) by @timgates42 + ## 1.7.2 ### Various fixes & improvements diff --git a/docs/conf.py b/docs/conf.py index 5bad71aa34..633b1438f8 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -29,7 +29,7 @@ copyright = "2019, Sentry Team and Contributors" author = "Sentry Team and Contributors" -release = "1.7.2" +release = "1.8.0" version = ".".join(release.split(".")[:2]) # The short X.Y version. diff --git a/pytest.ini b/pytest.ini index 4e987c1a90..f736c30496 100644 --- a/pytest.ini +++ b/pytest.ini @@ -3,7 +3,8 @@ DJANGO_SETTINGS_MODULE = tests.integrations.django.myapp.settings addopts = --tb=short markers = tests_internal_exceptions: Handle internal exceptions just as the SDK does, to test it. (Otherwise internal exceptions are recorded and reraised.) - only: A temporary marker, to make pytest only run the tests with the mark, similar to jest's `it.only`. To use, run `pytest -v -m only`. + only: A temporary marker, to make pytest only run the tests with the mark, similar to jests `it.only`. To use, run `pytest -v -m only`. +asyncio_mode = strict [pytest-watch] ; Enable this to drop into pdb on errors diff --git a/sentry_sdk/consts.py b/sentry_sdk/consts.py index 1624934b28..8dc4d16d63 100644 --- a/sentry_sdk/consts.py +++ b/sentry_sdk/consts.py @@ -102,7 +102,7 @@ def _get_default_options(): del _get_default_options -VERSION = "1.7.2" +VERSION = "1.8.0" SDK_INFO = { "name": "sentry.python", "version": VERSION, diff --git a/sentry_sdk/integrations/asgi.py b/sentry_sdk/integrations/asgi.py index 3aa9fcb572..125aad5b61 100644 --- a/sentry_sdk/integrations/asgi.py +++ b/sentry_sdk/integrations/asgi.py @@ -16,14 +16,13 @@ from sentry_sdk.tracing import ( SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE, - TRANSACTION_SOURCE_UNKNOWN, ) from sentry_sdk.utils import ( ContextVar, event_from_exception, - transaction_from_function, HAS_REAL_CONTEXTVARS, CONTEXTVARS_ERROR_MESSAGE, + transaction_from_function, ) from sentry_sdk.tracing import Transaction @@ -45,15 +44,15 @@ TRANSACTION_STYLE_VALUES = ("endpoint", "url") -def _capture_exception(hub, exc): - # type: (Hub, Any) -> None +def _capture_exception(hub, exc, mechanism_type="asgi"): + # type: (Hub, Any, str) -> None # Check client here as it might have been unset while streaming response if hub.client is not None: event, hint = event_from_exception( exc, client_options=hub.client.options, - mechanism={"type": "asgi", "handled": False}, + mechanism={"type": mechanism_type, "handled": False}, ) hub.capture_event(event, hint=hint) @@ -75,10 +74,16 @@ def _looks_like_asgi3(app): class SentryAsgiMiddleware: - __slots__ = ("app", "__call__", "transaction_style") - - def __init__(self, app, unsafe_context_data=False, transaction_style="endpoint"): - # type: (Any, bool, str) -> None + __slots__ = ("app", "__call__", "transaction_style", "mechanism_type") + + def __init__( + self, + app, + unsafe_context_data=False, + transaction_style="endpoint", + mechanism_type="asgi", + ): + # type: (Any, bool, str, str) -> None """ Instrument an ASGI application with Sentry. Provides HTTP/websocket data to sent events and basic handling for exceptions bubbling up @@ -100,6 +105,7 @@ def __init__(self, app, unsafe_context_data=False, transaction_style="endpoint") % (transaction_style, TRANSACTION_STYLE_VALUES) ) self.transaction_style = transaction_style + self.mechanism_type = mechanism_type self.app = app if _looks_like_asgi3(app): @@ -127,7 +133,7 @@ async def _run_app(self, scope, callback): try: return await callback() except Exception as exc: - _capture_exception(Hub.current, exc) + _capture_exception(Hub.current, exc, mechanism_type=self.mechanism_type) raise exc from None _asgi_middleware_applied.set(True) @@ -164,7 +170,9 @@ async def _run_app(self, scope, callback): try: return await callback() except Exception as exc: - _capture_exception(hub, exc) + _capture_exception( + hub, exc, mechanism_type=self.mechanism_type + ) raise exc from None finally: _asgi_middleware_applied.set(False) @@ -203,7 +211,6 @@ def event_processor(self, event, hint, asgi_scope): def _set_transaction_name_and_source(self, event, transaction_style, asgi_scope): # type: (Event, str, Any) -> None - transaction_name_already_set = ( event.get("transaction", _DEFAULT_TRANSACTION_NAME) != _DEFAULT_TRANSACTION_NAME @@ -231,9 +238,8 @@ def _set_transaction_name_and_source(self, event, transaction_style, asgi_scope) name = path if not name: - # If no transaction name can be found set an unknown source. - # This can happen when ASGI frameworks that are not yet supported well are used. - event["transaction_info"] = {"source": TRANSACTION_SOURCE_UNKNOWN} + event["transaction"] = _DEFAULT_TRANSACTION_NAME + event["transaction_info"] = {"source": TRANSACTION_SOURCE_ROUTE} return event["transaction"] = name diff --git a/sentry_sdk/integrations/fastapi.py b/sentry_sdk/integrations/fastapi.py new file mode 100644 index 0000000000..c5fa4e84e2 --- /dev/null +++ b/sentry_sdk/integrations/fastapi.py @@ -0,0 +1,122 @@ +from sentry_sdk._types import MYPY +from sentry_sdk.hub import Hub +from sentry_sdk.integrations import DidNotEnable +from sentry_sdk.integrations.starlette import ( + SentryStarletteMiddleware, + StarletteIntegration, +) +from sentry_sdk.tracing import SOURCE_FOR_STYLE, TRANSACTION_SOURCE_ROUTE +from sentry_sdk.utils import transaction_from_function + +if MYPY: + from typing import Any, Callable, Dict + + from sentry_sdk._types import Event + +try: + from fastapi import FastAPI # type: ignore + from fastapi import Request +except ImportError: + raise DidNotEnable("FastAPI is not installed") + +try: + from starlette.types import ASGIApp, Receive, Scope, Send # type: ignore +except ImportError: + raise DidNotEnable("Starlette is not installed") + + +_DEFAULT_TRANSACTION_NAME = "generic FastAPI request" + + +class FastApiIntegration(StarletteIntegration): + identifier = "fastapi" + + @staticmethod + def setup_once(): + # type: () -> None + StarletteIntegration.setup_once() + patch_middlewares() + + +def patch_middlewares(): + # type: () -> None + + old_build_middleware_stack = FastAPI.build_middleware_stack + + def _sentry_build_middleware_stack(self): + # type: (FastAPI) -> Callable[..., Any] + """ + Adds `SentryStarletteMiddleware` and `SentryFastApiMiddleware` to the + middleware stack of the FastAPI application. + """ + app = old_build_middleware_stack(self) + app = SentryStarletteMiddleware(app=app) + app = SentryFastApiMiddleware(app=app) + return app + + FastAPI.build_middleware_stack = _sentry_build_middleware_stack + + +def _set_transaction_name_and_source(event, transaction_style, request): + # type: (Event, str, Any) -> None + name = "" + + if transaction_style == "endpoint": + endpoint = request.scope.get("endpoint") + if endpoint: + name = transaction_from_function(endpoint) or "" + + elif transaction_style == "url": + route = request.scope.get("route") + if route: + path = getattr(route, "path", None) + if path is not None: + name = path + + if not name: + event["transaction"] = _DEFAULT_TRANSACTION_NAME + event["transaction_info"] = {"source": TRANSACTION_SOURCE_ROUTE} + return + + event["transaction"] = name + event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]} + + +class SentryFastApiMiddleware: + def __init__(self, app, dispatch=None): + # type: (ASGIApp, Any) -> None + self.app = app + + async def __call__(self, scope, receive, send): + # type: (Scope, Receive, Send) -> Any + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + hub = Hub.current + integration = hub.get_integration(FastApiIntegration) + if integration is None: + return + + with hub.configure_scope() as sentry_scope: + request = Request(scope, receive=receive, send=send) + + def _make_request_event_processor(req, integration): + # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]] + def event_processor(event, hint): + # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] + + _set_transaction_name_and_source( + event, integration.transaction_style, req + ) + + return event + + return event_processor + + sentry_scope._name = FastApiIntegration.identifier + sentry_scope.add_event_processor( + _make_request_event_processor(request, integration) + ) + + await self.app(scope, receive, send) diff --git a/sentry_sdk/integrations/starlette.py b/sentry_sdk/integrations/starlette.py new file mode 100644 index 0000000000..5fa8719e75 --- /dev/null +++ b/sentry_sdk/integrations/starlette.py @@ -0,0 +1,461 @@ +from __future__ import absolute_import + + +from sentry_sdk._compat import iteritems +from sentry_sdk._types import MYPY +from sentry_sdk.hub import Hub, _should_send_default_pii +from sentry_sdk.integrations import DidNotEnable, Integration +from sentry_sdk.integrations._wsgi_common import ( + _is_json_content_type, + request_body_within_bounds, +) +from sentry_sdk.integrations.asgi import SentryAsgiMiddleware +from sentry_sdk.tracing import SOURCE_FOR_STYLE +from sentry_sdk.utils import ( + TRANSACTION_SOURCE_ROUTE, + AnnotatedValue, + event_from_exception, + transaction_from_function, +) + +if MYPY: + from typing import Any, Awaitable, Callable, Dict, Optional, Union + + from sentry_sdk._types import Event + +try: + from starlette.applications import Starlette # type: ignore + from starlette.datastructures import UploadFile # type: ignore + from starlette.middleware import Middleware # type: ignore + from starlette.middleware.authentication import AuthenticationMiddleware # type: ignore + from starlette.requests import Request # type: ignore + from starlette.routing import Match # type: ignore + from starlette.types import ASGIApp, Receive, Scope, Send # type: ignore +except ImportError: + raise DidNotEnable("Starlette is not installed") + +try: + # Starlette 0.20 + from starlette.middleware.exceptions import ExceptionMiddleware # type: ignore +except ImportError: + # Startlette 0.19.1 + from starlette.exceptions import ExceptionMiddleware # type: ignore + + +_DEFAULT_TRANSACTION_NAME = "generic Starlette request" + +TRANSACTION_STYLE_VALUES = ("endpoint", "url") + + +class StarletteIntegration(Integration): + identifier = "starlette" + + transaction_style = "" + + def __init__(self, transaction_style="url"): + # type: (str) -> None + if transaction_style not in TRANSACTION_STYLE_VALUES: + raise ValueError( + "Invalid value for transaction_style: %s (must be in %s)" + % (transaction_style, TRANSACTION_STYLE_VALUES) + ) + self.transaction_style = transaction_style + + @staticmethod + def setup_once(): + # type: () -> None + patch_middlewares() + patch_asgi_app() + + +def _enable_span_for_middleware(middleware_class): + # type: (Any) -> type + old_call = middleware_class.__call__ + + async def _create_span_call(*args, **kwargs): + # type: (Any, Any) -> None + hub = Hub.current + integration = hub.get_integration(StarletteIntegration) + if integration is not None: + middleware_name = args[0].__class__.__name__ + with hub.start_span( + op="starlette.middleware", description=middleware_name + ) as middleware_span: + middleware_span.set_tag("starlette.middleware_name", middleware_name) + + await old_call(*args, **kwargs) + + else: + await old_call(*args, **kwargs) + + not_yet_patched = old_call.__name__ not in [ + "_create_span_call", + "_sentry_authenticationmiddleware_call", + "_sentry_exceptionmiddleware_call", + ] + + if not_yet_patched: + middleware_class.__call__ = _create_span_call + + return middleware_class + + +def _capture_exception(exception, handled=False): + # type: (BaseException, **Any) -> None + hub = Hub.current + if hub.get_integration(StarletteIntegration) is None: + return + + event, hint = event_from_exception( + exception, + client_options=hub.client.options if hub.client else None, + mechanism={"type": StarletteIntegration.identifier, "handled": handled}, + ) + + hub.capture_event(event, hint=hint) + + +def patch_exception_middleware(middleware_class): + # type: (Any) -> None + """ + Capture all exceptions in Starlette app and + also extract user information. + """ + old_middleware_init = middleware_class.__init__ + + def _sentry_middleware_init(self, *args, **kwargs): + # type: (Any, Any, Any) -> None + old_middleware_init(self, *args, **kwargs) + + # Patch existing exception handlers + for key in self._exception_handlers.keys(): + old_handler = self._exception_handlers.get(key) + + def _sentry_patched_exception_handler(self, *args, **kwargs): + # type: (Any, Any, Any) -> None + exp = args[0] + _capture_exception(exp, handled=True) + return old_handler(self, *args, **kwargs) + + self._exception_handlers[key] = _sentry_patched_exception_handler + + middleware_class.__init__ = _sentry_middleware_init + + old_call = middleware_class.__call__ + + async def _sentry_exceptionmiddleware_call(self, scope, receive, send): + # type: (Dict[str, Any], Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]) -> None + # Also add the user (that was eventually set by be Authentication middle + # that was called before this middleware). This is done because the authentication + # middleware sets the user in the scope and then (in the same function) + # calls this exception middelware. In case there is no exception (or no handler + # for the type of exception occuring) then the exception bubbles up and setting the + # user information into the sentry scope is done in auth middleware and the + # ASGI middleware will then send everything to Sentry and this is fine. + # But if there is an exception happening that the exception middleware here + # has a handler for, it will send the exception directly to Sentry, so we need + # the user information right now. + # This is why we do it here. + _add_user_to_sentry_scope(scope) + await old_call(self, scope, receive, send) + + middleware_class.__call__ = _sentry_exceptionmiddleware_call + + +def _add_user_to_sentry_scope(scope): + # type: (Dict[str, Any]) -> None + """ + Extracts user information from the ASGI scope and + adds it to Sentry's scope. + """ + if "user" not in scope: + return + + if not _should_send_default_pii(): + return + + hub = Hub.current + if hub.get_integration(StarletteIntegration) is None: + return + + with hub.configure_scope() as sentry_scope: + user_info = {} # type: Dict[str, Any] + starlette_user = scope["user"] + + username = getattr(starlette_user, "username", None) + if username: + user_info.setdefault("username", starlette_user.username) + + user_id = getattr(starlette_user, "id", None) + if user_id: + user_info.setdefault("id", starlette_user.id) + + email = getattr(starlette_user, "email", None) + if email: + user_info.setdefault("email", starlette_user.email) + + sentry_scope.user = user_info + + +def patch_authentication_middleware(middleware_class): + # type: (Any) -> None + """ + Add user information to Sentry scope. + """ + old_call = middleware_class.__call__ + + async def _sentry_authenticationmiddleware_call(self, scope, receive, send): + # type: (Dict[str, Any], Dict[str, Any], Callable[[], Awaitable[Dict[str, Any]]], Callable[[Dict[str, Any]], Awaitable[None]]) -> None + await old_call(self, scope, receive, send) + _add_user_to_sentry_scope(scope) + + middleware_class.__call__ = _sentry_authenticationmiddleware_call + + +def patch_middlewares(): + # type: () -> None + """ + Patches Starlettes `Middleware` class to record + spans for every middleware invoked. + """ + old_middleware_init = Middleware.__init__ + + def _sentry_middleware_init(self, cls, **options): + # type: (Any, Any, Any) -> None + span_enabled_cls = _enable_span_for_middleware(cls) + old_middleware_init(self, span_enabled_cls, **options) + + if cls == AuthenticationMiddleware: + patch_authentication_middleware(cls) + + if cls == ExceptionMiddleware: + patch_exception_middleware(cls) + + Middleware.__init__ = _sentry_middleware_init + + old_build_middleware_stack = Starlette.build_middleware_stack + + def _sentry_build_middleware_stack(self): + # type: (Starlette) -> Callable[..., Any] + """ + Adds `SentryStarletteMiddleware` to the + middleware stack of the Starlette application. + """ + app = old_build_middleware_stack(self) + app = SentryStarletteMiddleware(app=app) + return app + + Starlette.build_middleware_stack = _sentry_build_middleware_stack + + +def patch_asgi_app(): + # type: () -> None + """ + Instrument Starlette ASGI app using the SentryAsgiMiddleware. + """ + old_app = Starlette.__call__ + + async def _sentry_patched_asgi_app(self, scope, receive, send): + # type: (Starlette, Scope, Receive, Send) -> None + if Hub.current.get_integration(StarletteIntegration) is None: + return await old_app(self, scope, receive, send) + + middleware = SentryAsgiMiddleware( + lambda *a, **kw: old_app(self, *a, **kw), + mechanism_type=StarletteIntegration.identifier, + ) + middleware.__call__ = middleware._run_asgi3 + return await middleware(scope, receive, send) + + Starlette.__call__ = _sentry_patched_asgi_app + + +class StarletteRequestExtractor: + """ + Extracts useful information from the Starlette request + (like form data or cookies) and adds it to the Sentry event. + """ + + request = None # type: Request + + def __init__(self, request): + # type: (StarletteRequestExtractor, Request) -> None + self.request = request + + async def extract_request_info(self): + # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] + client = Hub.current.client + if client is None: + return None + + data = None # type: Union[Dict[str, Any], AnnotatedValue, None] + + content_length = await self.content_length() + request_info = {} # type: Dict[str, Any] + + if _should_send_default_pii(): + request_info["cookies"] = self.cookies() + + if not request_body_within_bounds(client, content_length): + data = AnnotatedValue( + "", + {"rem": [["!config", "x", 0, content_length]], "len": content_length}, + ) + else: + parsed_body = await self.parsed_body() + if parsed_body is not None: + data = parsed_body + elif await self.raw_data(): + data = AnnotatedValue( + "", + {"rem": [["!raw", "x", 0, content_length]], "len": content_length}, + ) + else: + data = None + + if data is not None: + request_info["data"] = data + + return request_info + + async def content_length(self): + # type: (StarletteRequestExtractor) -> int + raw_data = await self.raw_data() + if raw_data is None: + return 0 + return len(raw_data) + + def cookies(self): + # type: (StarletteRequestExtractor) -> Dict[str, Any] + return self.request.cookies + + async def raw_data(self): + # type: (StarletteRequestExtractor) -> Any + return await self.request.body() + + async def form(self): + # type: (StarletteRequestExtractor) -> Any + """ + curl -X POST http://localhost:8000/upload/somethign -H "Content-Type: application/x-www-form-urlencoded" -d "username=kevin&password=welcome123" + curl -X POST http://localhost:8000/upload/somethign -F username=Julian -F password=hello123 + """ + return await self.request.form() + + def is_json(self): + # type: (StarletteRequestExtractor) -> bool + return _is_json_content_type(self.request.headers.get("content-type")) + + async def json(self): + # type: (StarletteRequestExtractor) -> Optional[Dict[str, Any]] + """ + curl -X POST localhost:8000/upload/something -H 'Content-Type: application/json' -d '{"login":"my_login","password":"my_password"}' + """ + if not self.is_json(): + return None + + return await self.request.json() + + async def parsed_body(self): + # type: (StarletteRequestExtractor) -> Any + """ + curl -X POST http://localhost:8000/upload/somethign -F username=Julian -F password=hello123 -F photo=@photo.jpg + """ + form = await self.form() + if form: + data = {} + for key, val in iteritems(form): + if isinstance(val, UploadFile): + size = len(await val.read()) + data[key] = AnnotatedValue( + "", {"len": size, "rem": [["!raw", "x", 0, size]]} + ) + else: + data[key] = val + + return data + + json_data = await self.json() + return json_data + + +def _set_transaction_name_and_source(event, transaction_style, request): + # type: (Event, str, Any) -> None + name = "" + + if transaction_style == "endpoint": + endpoint = request.scope.get("endpoint") + if endpoint: + name = transaction_from_function(endpoint) or "" + + elif transaction_style == "url": + router = request.scope["router"] + for route in router.routes: + match = route.matches(request.scope) + + if match[0] == Match.FULL: + if transaction_style == "endpoint": + name = transaction_from_function(match[1]["endpoint"]) or "" + break + elif transaction_style == "url": + name = route.path + break + + if not name: + event["transaction"] = _DEFAULT_TRANSACTION_NAME + event["transaction_info"] = {"source": TRANSACTION_SOURCE_ROUTE} + return + + event["transaction"] = name + event["transaction_info"] = {"source": SOURCE_FOR_STYLE[transaction_style]} + + +class SentryStarletteMiddleware: + def __init__(self, app, dispatch=None): + # type: (ASGIApp, Any) -> None + self.app = app + + async def __call__(self, scope, receive, send): + # type: (Scope, Receive, Send) -> Any + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + hub = Hub.current + integration = hub.get_integration(StarletteIntegration) + if integration is None: + return + + with hub.configure_scope() as sentry_scope: + request = Request(scope, receive=receive, send=send) + + extractor = StarletteRequestExtractor(request) + info = await extractor.extract_request_info() + + def _make_request_event_processor(req, integration): + # type: (Any, Any) -> Callable[[Dict[str, Any], Dict[str, Any]], Dict[str, Any]] + def event_processor(event, hint): + # type: (Dict[str, Any], Dict[str, Any]) -> Dict[str, Any] + + # Extract information from request + request_info = event.get("request", {}) + if info: + if "cookies" in info and _should_send_default_pii(): + request_info["cookies"] = info["cookies"] + if "data" in info: + request_info["data"] = info["data"] + event["request"] = request_info + + _set_transaction_name_and_source( + event, integration.transaction_style, req + ) + + return event + + return event_processor + + sentry_scope._name = StarletteIntegration.identifier + sentry_scope.add_event_processor( + _make_request_event_processor(request, integration) + ) + + await self.app(scope, receive, send) diff --git a/sentry_sdk/tracing.py b/sentry_sdk/tracing.py index dd4b1a730d..410b8c3ad4 100644 --- a/sentry_sdk/tracing.py +++ b/sentry_sdk/tracing.py @@ -279,7 +279,7 @@ def continue_from_headers( if sentrytrace_kwargs is not None: kwargs.update(sentrytrace_kwargs) - baggage.freeze + baggage.freeze() kwargs.update(extract_tracestate_data(headers.get("tracestate"))) @@ -308,7 +308,9 @@ def iter_headers(self): yield "tracestate", tracestate if self.containing_transaction and self.containing_transaction._baggage: - yield "baggage", self.containing_transaction._baggage.serialize() + baggage = self.containing_transaction._baggage.serialize() + if baggage: + yield "baggage", baggage @classmethod def from_traceparent( diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index ccac6e37e3..6307e6b6f9 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -42,6 +42,16 @@ MAX_STRING_LENGTH = 512 BASE64_ALPHABET = re.compile(r"^[a-zA-Z0-9/+=]*$") +# Transaction source +# see https://develop.sentry.dev/sdk/event-payloads/transaction/#transaction-annotations +TRANSACTION_SOURCE_CUSTOM = "custom" +TRANSACTION_SOURCE_URL = "url" +TRANSACTION_SOURCE_ROUTE = "route" +TRANSACTION_SOURCE_VIEW = "view" +TRANSACTION_SOURCE_COMPONENT = "component" +TRANSACTION_SOURCE_TASK = "task" +TRANSACTION_SOURCE_UNKNOWN = "unknown" + def json_dumps(data): # type: (Any) -> bytes diff --git a/setup.py b/setup.py index d71f9f750a..e476f0caf8 100644 --- a/setup.py +++ b/setup.py @@ -21,7 +21,7 @@ def get_file_text(file_name): setup( name="sentry-sdk", - version="1.7.2", + version="1.8.0", author="Sentry Team and Contributors", author_email="hello@sentry.io", url="https://github.com/getsentry/sentry-python", @@ -55,6 +55,8 @@ def get_file_text(file_name): "pure_eval": ["pure_eval", "executing", "asttokens"], "chalice": ["chalice>=1.16.0"], "httpx": ["httpx>=0.16.0"], + "starlette": ["starlette>=0.19.1"], + "fastapi": ["fastapi>=0.79.0"], }, classifiers=[ "Development Status :: 5 - Production/Stable", diff --git a/tests/integrations/asgi/test_asgi.py b/tests/integrations/asgi/test_asgi.py index aed2157612..a5687f86ad 100644 --- a/tests/integrations/asgi/test_asgi.py +++ b/tests/integrations/asgi/test_asgi.py @@ -270,7 +270,7 @@ def kangaroo_handler(request): "/sync-message", "url", "generic ASGI request", # the AsgiMiddleware can not extract routes from the Starlette framework used here for testing. - "unknown", + "route", ), ( "/sync-message/123456", @@ -282,7 +282,7 @@ def kangaroo_handler(request): "/sync-message/123456", "url", "generic ASGI request", # the AsgiMiddleware can not extract routes from the Starlette framework used here for testing. - "unknown", + "route", ), ( "/async-message", @@ -294,7 +294,7 @@ def kangaroo_handler(request): "/async-message", "url", "generic ASGI request", # the AsgiMiddleware can not extract routes from the Starlette framework used here for testing. - "unknown", + "route", ), ], ) diff --git a/tests/integrations/asgi/test_fastapi.py b/tests/integrations/asgi/test_fastapi.py deleted file mode 100644 index 518b8544b2..0000000000 --- a/tests/integrations/asgi/test_fastapi.py +++ /dev/null @@ -1,46 +0,0 @@ -import sys - -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient -from sentry_sdk import capture_message -from sentry_sdk.integrations.asgi import SentryAsgiMiddleware - - -@pytest.fixture -def app(): - app = FastAPI() - - @app.get("/users/{user_id}") - async def get_user(user_id: str): - capture_message("hi", level="error") - return {"user_id": user_id} - - app.add_middleware(SentryAsgiMiddleware, transaction_style="url") - - return app - - -@pytest.mark.skipif(sys.version_info < (3, 7), reason="requires python3.7 or higher") -def test_fastapi_transaction_style(sentry_init, app, capture_events): - sentry_init(send_default_pii=True) - events = capture_events() - - client = TestClient(app) - response = client.get("/users/rick") - - assert response.status_code == 200 - - (event,) = events - assert event["transaction"] == "/users/{user_id}" - assert event["request"]["env"] == {"REMOTE_ADDR": "testclient"} - assert event["request"]["url"].endswith("/users/rick") - assert event["request"]["method"] == "GET" - - # Assert that state is not leaked - events.clear() - capture_message("foo") - (event,) = events - - assert "request" not in event - assert "transaction" not in event diff --git a/tests/integrations/fastapi/__init__.py b/tests/integrations/fastapi/__init__.py new file mode 100644 index 0000000000..7f667e6f75 --- /dev/null +++ b/tests/integrations/fastapi/__init__.py @@ -0,0 +1,3 @@ +import pytest + +pytest.importorskip("fastapi") diff --git a/tests/integrations/fastapi/test_fastapi.py b/tests/integrations/fastapi/test_fastapi.py new file mode 100644 index 0000000000..86f7db8cad --- /dev/null +++ b/tests/integrations/fastapi/test_fastapi.py @@ -0,0 +1,142 @@ +import pytest +from sentry_sdk.integrations.fastapi import FastApiIntegration + +fastapi = pytest.importorskip("fastapi") + +from fastapi import FastAPI +from fastapi.testclient import TestClient +from sentry_sdk import capture_message +from sentry_sdk.integrations.starlette import StarletteIntegration +from sentry_sdk.integrations.asgi import SentryAsgiMiddleware + + +def fastapi_app_factory(): + app = FastAPI() + + @app.get("/message") + async def _message(): + capture_message("Hi") + return {"message": "Hi"} + + @app.get("/message/{message_id}") + async def _message_with_id(message_id): + capture_message("Hi") + return {"message": "Hi"} + + return app + + +@pytest.mark.asyncio +async def test_response(sentry_init, capture_events): + # FastAPI is heavily based on Starlette so we also need + # to enable StarletteIntegration. + # In the future this will be auto enabled. + sentry_init( + integrations=[StarletteIntegration(), FastApiIntegration()], + traces_sample_rate=1.0, + send_default_pii=True, + debug=True, + ) + + app = fastapi_app_factory() + + events = capture_events() + + client = TestClient(app) + response = client.get("/message") + + assert response.json() == {"message": "Hi"} + + assert len(events) == 2 + + (message_event, transaction_event) = events + assert message_event["message"] == "Hi" + assert transaction_event["transaction"] == "/message" + + +@pytest.mark.parametrize( + "url,transaction_style,expected_transaction,expected_source", + [ + ( + "/message", + "url", + "/message", + "route", + ), + ( + "/message", + "endpoint", + "tests.integrations.fastapi.test_fastapi.fastapi_app_factory.._message", + "component", + ), + ( + "/message/123456", + "url", + "/message/{message_id}", + "route", + ), + ( + "/message/123456", + "endpoint", + "tests.integrations.fastapi.test_fastapi.fastapi_app_factory.._message_with_id", + "component", + ), + ], +) +def test_transaction_style( + sentry_init, + capture_events, + url, + transaction_style, + expected_transaction, + expected_source, +): + sentry_init( + integrations=[ + StarletteIntegration(transaction_style=transaction_style), + FastApiIntegration(transaction_style=transaction_style), + ], + ) + app = fastapi_app_factory() + + events = capture_events() + + client = TestClient(app) + client.get(url) + + (event,) = events + assert event["transaction"] == expected_transaction + assert event["transaction_info"] == {"source": expected_source} + + # Assert that state is not leaked + events.clear() + capture_message("foo") + (event,) = events + + assert "request" not in event + assert "transaction" not in event + + +def test_legacy_setup( + sentry_init, + capture_events, +): + # Check that behaviour does not change + # if the user just adds the new Integrations + # and forgets to remove SentryAsgiMiddleware + sentry_init( + integrations=[ + StarletteIntegration(), + FastApiIntegration(), + ], + ) + app = fastapi_app_factory() + asgi_app = SentryAsgiMiddleware(app) + + events = capture_events() + + client = TestClient(asgi_app) + client.get("/message/123456") + + (event,) = events + assert event["transaction"] == "/message/{message_id}" diff --git a/tests/integrations/starlette/__init__.py b/tests/integrations/starlette/__init__.py new file mode 100644 index 0000000000..c89ddf99a8 --- /dev/null +++ b/tests/integrations/starlette/__init__.py @@ -0,0 +1,3 @@ +import pytest + +pytest.importorskip("starlette") diff --git a/tests/integrations/starlette/photo.jpg b/tests/integrations/starlette/photo.jpg new file mode 100644 index 0000000000..52fbeef721 Binary files /dev/null and b/tests/integrations/starlette/photo.jpg differ diff --git a/tests/integrations/starlette/test_starlette.py b/tests/integrations/starlette/test_starlette.py new file mode 100644 index 0000000000..16c1dfb67b --- /dev/null +++ b/tests/integrations/starlette/test_starlette.py @@ -0,0 +1,567 @@ +import asyncio +import base64 +import json +import os + +import pytest + +from sentry_sdk.integrations.asgi import SentryAsgiMiddleware + +try: + from unittest import mock # python 3.3 and above +except ImportError: + import mock # python < 3.3 + +from sentry_sdk import capture_message +from sentry_sdk.integrations.starlette import ( + StarletteIntegration, + StarletteRequestExtractor, +) +from sentry_sdk.utils import AnnotatedValue + +starlette = pytest.importorskip("starlette") +from starlette.authentication import ( + AuthCredentials, + AuthenticationBackend, + AuthenticationError, + SimpleUser, +) +from starlette.middleware import Middleware +from starlette.middleware.authentication import AuthenticationMiddleware +from starlette.testclient import TestClient + +PICTURE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "photo.jpg") + +BODY_JSON = {"some": "json", "for": "testing", "nested": {"numbers": 123}} + +BODY_FORM = """--fd721ef49ea403a6\r\nContent-Disposition: form-data; name="username"\r\n\r\nJane\r\n--fd721ef49ea403a6\r\nContent-Disposition: form-data; name="password"\r\n\r\nhello123\r\n--fd721ef49ea403a6\r\nContent-Disposition: form-data; name="photo"; filename="photo.jpg"\r\nContent-Type: image/jpg\r\nContent-Transfer-Encoding: base64\r\n\r\n{{image_data}}\r\n--fd721ef49ea403a6--\r\n""".replace( + "{{image_data}}", str(base64.b64encode(open(PICTURE, "rb").read())) +) + +PARSED_FORM = starlette.datastructures.FormData( + [ + ("username", "Jane"), + ("password", "hello123"), + ( + "photo", + starlette.datastructures.UploadFile( + filename="photo.jpg", + file=open(PICTURE, "rb"), + content_type="image/jpeg", + ), + ), + ] +) +PARSED_BODY = { + "username": "Jane", + "password": "hello123", + "photo": AnnotatedValue( + "", {"len": 28023, "rem": [["!raw", "x", 0, 28023]]} + ), # size of photo.jpg read above +} + +# Dummy ASGI scope for creating mock Starlette requests +SCOPE = { + "client": ("172.29.0.10", 34784), + "headers": [ + [b"host", b"example.com"], + [b"user-agent", b"Mozilla/5.0 Gecko/20100101 Firefox/60.0"], + [b"content-type", b"application/json"], + [b"accept-language", b"en-US,en;q=0.5"], + [b"accept-encoding", b"gzip, deflate, br"], + [b"upgrade-insecure-requests", b"1"], + [b"cookie", b"yummy_cookie=choco; tasty_cookie=strawberry"], + ], + "http_version": "0.0", + "method": "GET", + "path": "/path", + "query_string": b"qs=hello", + "scheme": "http", + "server": ("172.28.0.10", 8000), + "type": "http", +} + + +def starlette_app_factory(middleware=None): + async def _homepage(request): + 1 / 0 + return starlette.responses.JSONResponse({"status": "ok"}) + + async def _custom_error(request): + raise Exception("Too Hot") + + async def _message(request): + capture_message("hi") + return starlette.responses.JSONResponse({"status": "ok"}) + + async def _message_with_id(request): + capture_message("hi") + return starlette.responses.JSONResponse({"status": "ok"}) + + app = starlette.applications.Starlette( + debug=True, + routes=[ + starlette.routing.Route("/some_url", _homepage), + starlette.routing.Route("/custom_error", _custom_error), + starlette.routing.Route("/message", _message), + starlette.routing.Route("/message/{message_id}", _message_with_id), + ], + middleware=middleware, + ) + + return app + + +def async_return(result): + f = asyncio.Future() + f.set_result(result) + return f + + +class BasicAuthBackend(AuthenticationBackend): + async def authenticate(self, conn): + if "Authorization" not in conn.headers: + return + + auth = conn.headers["Authorization"] + try: + scheme, credentials = auth.split() + if scheme.lower() != "basic": + return + decoded = base64.b64decode(credentials).decode("ascii") + except (ValueError, UnicodeDecodeError): + raise AuthenticationError("Invalid basic auth credentials") + + username, _, password = decoded.partition(":") + + # TODO: You'd want to verify the username and password here. + + return AuthCredentials(["authenticated"]), SimpleUser(username) + + +class AsyncIterator: + def __init__(self, data): + self.iter = iter(bytes(data, "utf-8")) + + def __aiter__(self): + return self + + async def __anext__(self): + try: + return bytes([next(self.iter)]) + except StopIteration: + raise StopAsyncIteration + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_content_length(sentry_init): + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(json.dumps(BODY_JSON)), + ): + starlette_request = starlette.requests.Request(SCOPE) + extractor = StarletteRequestExtractor(starlette_request) + + assert await extractor.content_length() == len(json.dumps(BODY_JSON)) + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_cookies(sentry_init): + starlette_request = starlette.requests.Request(SCOPE) + extractor = StarletteRequestExtractor(starlette_request) + + assert extractor.cookies() == { + "tasty_cookie": "strawberry", + "yummy_cookie": "choco", + } + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_json(sentry_init): + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(json.dumps(BODY_JSON)), + ): + starlette_request = starlette.requests.Request(SCOPE) + extractor = StarletteRequestExtractor(starlette_request) + + assert extractor.is_json() + assert await extractor.json() == BODY_JSON + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_parsed_body_json(sentry_init): + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(json.dumps(BODY_JSON)), + ): + starlette_request = starlette.requests.Request(SCOPE) + extractor = StarletteRequestExtractor(starlette_request) + + parsed_body = await extractor.parsed_body() + assert parsed_body == BODY_JSON + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_parsed_body_form(sentry_init): + scope = SCOPE.copy() + scope["headers"] = [ + [b"content-type", b"multipart/form-data; boundary=fd721ef49ea403a6"], + ] + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(BODY_FORM), + ): + starlette_request = starlette.requests.Request(scope) + extractor = StarletteRequestExtractor(starlette_request) + + parsed_body = await extractor.parsed_body() + assert parsed_body.keys() == PARSED_BODY.keys() + assert parsed_body["username"] == PARSED_BODY["username"] + assert parsed_body["password"] == PARSED_BODY["password"] + assert parsed_body["photo"].metadata == PARSED_BODY["photo"].metadata + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_form(sentry_init): + scope = SCOPE.copy() + scope["headers"] = [ + [b"content-type", b"multipart/form-data; boundary=fd721ef49ea403a6"], + ] + # TODO add test for content-type: "application/x-www-form-urlencoded" + + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(BODY_FORM), + ): + starlette_request = starlette.requests.Request(scope) + extractor = StarletteRequestExtractor(starlette_request) + + form_data = await extractor.form() + assert form_data.keys() == PARSED_FORM.keys() + assert form_data["username"] == PARSED_FORM["username"] + assert form_data["password"] == PARSED_FORM["password"] + assert form_data["photo"].filename == PARSED_FORM["photo"].filename + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_raw_data(sentry_init): + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(json.dumps(BODY_JSON)), + ): + starlette_request = starlette.requests.Request(SCOPE) + extractor = StarletteRequestExtractor(starlette_request) + + assert await extractor.raw_data() == bytes(json.dumps(BODY_JSON), "utf-8") + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_extract_request_info_too_big(sentry_init): + sentry_init( + send_default_pii=True, + integrations=[StarletteIntegration()], + ) + scope = SCOPE.copy() + scope["headers"] = [ + [b"content-type", b"multipart/form-data; boundary=fd721ef49ea403a6"], + [b"cookie", b"yummy_cookie=choco; tasty_cookie=strawberry"], + ] + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(BODY_FORM), + ): + starlette_request = starlette.requests.Request(scope) + extractor = StarletteRequestExtractor(starlette_request) + + request_info = await extractor.extract_request_info() + + assert request_info + assert request_info["cookies"] == { + "tasty_cookie": "strawberry", + "yummy_cookie": "choco", + } + # Because request is too big only the AnnotatedValue is extracted. + assert request_info["data"].metadata == { + "rem": [["!config", "x", 0, 28355]], + "len": 28355, + } + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_extract_request_info(sentry_init): + sentry_init( + send_default_pii=True, + integrations=[StarletteIntegration()], + ) + scope = SCOPE.copy() + scope["headers"] = [ + [b"content-type", b"application/json"], + [b"cookie", b"yummy_cookie=choco; tasty_cookie=strawberry"], + ] + + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(json.dumps(BODY_JSON)), + ): + starlette_request = starlette.requests.Request(scope) + extractor = StarletteRequestExtractor(starlette_request) + + request_info = await extractor.extract_request_info() + + assert request_info + assert request_info["cookies"] == { + "tasty_cookie": "strawberry", + "yummy_cookie": "choco", + } + assert request_info["data"] == BODY_JSON + + +@pytest.mark.asyncio +async def test_starlettrequestextractor_extract_request_info_no_pii(sentry_init): + sentry_init( + send_default_pii=False, + integrations=[StarletteIntegration()], + ) + scope = SCOPE.copy() + scope["headers"] = [ + [b"content-type", b"application/json"], + [b"cookie", b"yummy_cookie=choco; tasty_cookie=strawberry"], + ] + + with mock.patch( + "starlette.requests.Request.stream", + return_value=AsyncIterator(json.dumps(BODY_JSON)), + ): + starlette_request = starlette.requests.Request(scope) + extractor = StarletteRequestExtractor(starlette_request) + + request_info = await extractor.extract_request_info() + + assert request_info + assert "cookies" not in request_info + assert request_info["data"] == BODY_JSON + + +@pytest.mark.parametrize( + "url,transaction_style,expected_transaction,expected_source", + [ + ( + "/message", + "url", + "/message", + "route", + ), + ( + "/message", + "endpoint", + "tests.integrations.starlette.test_starlette.starlette_app_factory.._message", + "component", + ), + ( + "/message/123456", + "url", + "/message/{message_id}", + "route", + ), + ( + "/message/123456", + "endpoint", + "tests.integrations.starlette.test_starlette.starlette_app_factory.._message_with_id", + "component", + ), + ], +) +def test_transaction_style( + sentry_init, + capture_events, + url, + transaction_style, + expected_transaction, + expected_source, +): + sentry_init( + integrations=[StarletteIntegration(transaction_style=transaction_style)], + ) + starlette_app = starlette_app_factory() + + events = capture_events() + + client = TestClient(starlette_app) + client.get(url) + + (event,) = events + assert event["transaction"] == expected_transaction + assert event["transaction_info"] == {"source": expected_source} + + +@pytest.mark.parametrize( + "test_url,expected_error,expected_message", + [ + ("/some_url", ZeroDivisionError, "division by zero"), + ("/custom_error", Exception, "Too Hot"), + ], +) +def test_catch_exceptions( + sentry_init, + capture_exceptions, + capture_events, + test_url, + expected_error, + expected_message, +): + sentry_init(integrations=[StarletteIntegration()]) + starlette_app = starlette_app_factory() + exceptions = capture_exceptions() + events = capture_events() + + client = TestClient(starlette_app) + try: + client.get(test_url) + except Exception: + pass + + (exc,) = exceptions + assert isinstance(exc, expected_error) + assert str(exc) == expected_message + + (event,) = events + assert event["exception"]["values"][0]["mechanism"]["type"] == "starlette" + + +def test_user_information_error(sentry_init, capture_events): + sentry_init( + send_default_pii=True, + integrations=[StarletteIntegration()], + ) + starlette_app = starlette_app_factory( + middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())] + ) + events = capture_events() + + client = TestClient(starlette_app, raise_server_exceptions=False) + try: + client.get("/custom_error", auth=("Gabriela", "hello123")) + except Exception: + pass + + (event,) = events + user = event.get("user", None) + assert user + assert "username" in user + assert user["username"] == "Gabriela" + + +def test_user_information_error_no_pii(sentry_init, capture_events): + sentry_init( + send_default_pii=False, + integrations=[StarletteIntegration()], + ) + starlette_app = starlette_app_factory( + middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())] + ) + events = capture_events() + + client = TestClient(starlette_app, raise_server_exceptions=False) + try: + client.get("/custom_error", auth=("Gabriela", "hello123")) + except Exception: + pass + + (event,) = events + assert "user" not in event + + +def test_user_information_transaction(sentry_init, capture_events): + sentry_init( + traces_sample_rate=1.0, + send_default_pii=True, + integrations=[StarletteIntegration()], + ) + starlette_app = starlette_app_factory( + middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())] + ) + events = capture_events() + + client = TestClient(starlette_app, raise_server_exceptions=False) + client.get("/message", auth=("Gabriela", "hello123")) + + (_, transaction_event) = events + user = transaction_event.get("user", None) + assert user + assert "username" in user + assert user["username"] == "Gabriela" + + +def test_user_information_transaction_no_pii(sentry_init, capture_events): + sentry_init( + traces_sample_rate=1.0, + send_default_pii=False, + integrations=[StarletteIntegration()], + ) + starlette_app = starlette_app_factory( + middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())] + ) + events = capture_events() + + client = TestClient(starlette_app, raise_server_exceptions=False) + client.get("/message", auth=("Gabriela", "hello123")) + + (_, transaction_event) = events + assert "user" not in transaction_event + + +def test_middleware_spans(sentry_init, capture_events): + sentry_init( + traces_sample_rate=1.0, + integrations=[StarletteIntegration()], + ) + starlette_app = starlette_app_factory( + middleware=[Middleware(AuthenticationMiddleware, backend=BasicAuthBackend())] + ) + events = capture_events() + + client = TestClient(starlette_app, raise_server_exceptions=False) + try: + client.get("/message", auth=("Gabriela", "hello123")) + except Exception: + pass + + (_, transaction_event) = events + + expected = [ + "ServerErrorMiddleware", + "AuthenticationMiddleware", + "ExceptionMiddleware", + ] + + idx = 0 + for span in transaction_event["spans"]: + if span["op"] == "starlette.middleware": + assert span["description"] == expected[idx] + assert span["tags"]["starlette.middleware_name"] == expected[idx] + idx += 1 + + +def test_legacy_setup( + sentry_init, + capture_events, +): + # Check that behaviour does not change + # if the user just adds the new Integration + # and forgets to remove SentryAsgiMiddleware + sentry_init( + integrations=[ + StarletteIntegration(), + ], + ) + app = starlette_app_factory() + asgi_app = SentryAsgiMiddleware(app) + + events = capture_events() + + client = TestClient(asgi_app) + client.get("/message/123456") + + (event,) = events + assert event["transaction"] == "/message/{message_id}" diff --git a/tests/tracing/test_misc.py b/tests/tracing/test_misc.py index 43d9597f1b..b51b5dcddb 100644 --- a/tests/tracing/test_misc.py +++ b/tests/tracing/test_misc.py @@ -173,7 +173,7 @@ def test_circular_references(monkeypatch, sentry_init, request): # request.addfinalizer(lambda: gc.set_debug(~gc.DEBUG_LEAK)) # # immediately after the initial collection below, so we can see what new - # objects the garbage collecter has to clean up once `transaction.finish` is + # objects the garbage collector has to clean up once `transaction.finish` is # called and the serializer runs.) monkeypatch.setattr( sentry_sdk.client, diff --git a/tox.ini b/tox.ini index 570d13591f..d4e0e456cf 100644 --- a/tox.ini +++ b/tox.ini @@ -29,6 +29,12 @@ envlist = {pypy,py2.7,py3.5,py3.6,py3.7,py3.8,py3.9,py3.10}-flask-1.1 {py3.6,py3.8,py3.9,py3.10}-flask-2.0 + {py3.7,py3.8,py3.9,py3.10}-asgi + + {py3.7,py3.8,py3.9,py3.10}-starlette-{0.19.1,0.20} + + {py3.7,py3.8,py3.9,py3.10}-fastapi + {py3.7,py3.8,py3.9,py3.10}-quart {pypy,py2.7,py3.5,py3.6,py3.7,py3.8,py3.9,py3.10}-bottle-0.12 @@ -73,11 +79,8 @@ envlist = {py2.7,py3.7,py3.8,py3.9}-redis {py2.7,py3.7,py3.8,py3.9}-rediscluster-{1,2} - py{3.7,3.8,3.9,3.10}-asgi - {py2.7,py3.7,py3.8,py3.9,py3.10}-sqlalchemy-{1.2,1.3} - {py3.5,py3.6,py3.7,py3.8,py3.9,py3.10}-pure_eval {py3.6,py3.7,py3.8}-chalice-{1.16,1.17,1.18,1.19,1.20} @@ -128,6 +131,20 @@ deps = quart: quart-auth quart: pytest-asyncio + asgi: requests + asgi: starlette + + starlette: pytest-asyncio + starlette: python-multipart + starlette: requests + starlette-0.19.1: starlette==0.19.1 + starlette-0.20: starlette>=0.20.0,<0.21.0 + + fastapi: fastapi + fastapi: pytest-asyncio + fastapi: python-multipart + fastapi: requests + bottle-0.12: bottle>=0.12,<0.13 falcon-1.4: falcon>=1.4,<1.5 @@ -212,10 +229,6 @@ deps = rediscluster-1: redis-py-cluster>=1.0.0,<2.0.0 rediscluster-2: redis-py-cluster>=2.0.0,<3.0.0 - asgi: starlette - asgi: requests - asgi: fastapi - sqlalchemy-1.2: sqlalchemy>=1.2,<1.3 sqlalchemy-1.3: sqlalchemy>=1.3,<1.4 @@ -265,6 +278,8 @@ setenv = redis: TESTPATH=tests/integrations/redis rediscluster: TESTPATH=tests/integrations/rediscluster asgi: TESTPATH=tests/integrations/asgi + starlette: TESTPATH=tests/integrations/starlette + fastapi: TESTPATH=tests/integrations/fastapi sqlalchemy: TESTPATH=tests/integrations/sqlalchemy pure_eval: TESTPATH=tests/integrations/pure_eval chalice: TESTPATH=tests/integrations/chalice