diff --git a/examples/tracing/tracing.py b/examples/tracing/tracing.py index b5ed98044d..67defe637a 100644 --- a/examples/tracing/tracing.py +++ b/examples/tracing/tracing.py @@ -60,9 +60,8 @@ def wait(redis_key): result = redis_conn.get(redis_key) if result is None: return "NONE" - else: - redis_conn.delete(redis_key) - return "RESULT: {}".format(result) + redis_conn.delete(redis_key) + return "RESULT: {}".format(result) @app.cli.command("worker") diff --git a/sentry_sdk/attachments.py b/sentry_sdk/attachments.py index b7b6b0b45b..383fb4fc1a 100644 --- a/sentry_sdk/attachments.py +++ b/sentry_sdk/attachments.py @@ -37,10 +37,7 @@ def to_envelope_item(self): """Returns an envelope item for this attachment.""" payload = None # type: Union[None, PayloadRef, bytes] if self.bytes is not None: - if callable(self.bytes): - payload = self.bytes() - else: - payload = self.bytes + payload = self.bytes() if callable(self.bytes) else self.bytes else: payload = PayloadRef(path=self.path) return Item( diff --git a/sentry_sdk/client.py b/sentry_sdk/client.py index 659299c632..2d60f4819a 100644 --- a/sentry_sdk/client.py +++ b/sentry_sdk/client.py @@ -214,17 +214,13 @@ def _is_ignored_error(self, event, hint): type_name = get_type_name(exc_info[0]) full_name = "%s.%s" % (exc_info[0].__module__, type_name) - for errcls in self.options["ignore_errors"]: - # String types are matched against the type name in the - # exception only - if isinstance(errcls, string_types): - if errcls == full_name or errcls == type_name: - return True - else: - if issubclass(exc_info[0], errcls): - return True - - return False + return any( + isinstance(errcls, string_types) + and errcls in [full_name, type_name] + or not isinstance(errcls, string_types) + and issubclass(exc_info[0], errcls) + for errcls in self.options["ignore_errors"] + ) def _should_capture( self, @@ -249,10 +245,7 @@ def _should_capture( self.transport.record_lost_event("sample_rate", data_category="error") return False - if self._is_ignored_error(event, hint): - return False - - return True + return not self._is_ignored_error(event, hint) def _update_session_from_event( self, diff --git a/sentry_sdk/envelope.py b/sentry_sdk/envelope.py index ebb2842000..c8991ab1da 100644 --- a/sentry_sdk/envelope.py +++ b/sentry_sdk/envelope.py @@ -36,10 +36,7 @@ def __init__( if headers is not None: headers = dict(headers) self.headers = headers or {} - if items is None: - items = [] - else: - items = list(items) + items = [] if items is None else list(items) self.items = items @property @@ -196,10 +193,7 @@ def __init__( content_type=None, # type: Optional[str] filename=None, # type: Optional[str] ): - if headers is not None: - headers = dict(headers) - elif headers is None: - headers = {} + headers = dict(headers) if headers is not None else {} self.headers = headers if isinstance(payload, bytes): payload = PayloadRef(bytes=payload) diff --git a/sentry_sdk/hub.py b/sentry_sdk/hub.py index addca57417..e67b1b5def 100644 --- a/sentry_sdk/hub.py +++ b/sentry_sdk/hub.py @@ -104,8 +104,7 @@ def _init(*args, **kwargs): """ client = Client(*args, **kwargs) # type: ignore Hub.current.bind_client(client) - rv = _InitGuard(client) - return rv + return _InitGuard(client) from sentry_sdk._types import MYPY @@ -362,11 +361,7 @@ def capture_exception( client = self.client if client is None: return None - if error is not None: - exc_info = exc_info_from_error(error) - else: - exc_info = sys.exc_info() - + exc_info = exc_info_from_error(error) if error is not None else sys.exc_info() event, hint = event_from_exception(exc_info, client_options=client.options) try: return self.capture_event(event, hint=hint, scope=scope, **scope_args) @@ -458,13 +453,13 @@ def start_span( "Deprecated: use start_transaction to start transactions and " "Transaction.start_child to start spans." ) - if isinstance(span, Transaction): - logger.warning(deprecation_msg) - return self.start_transaction(span) - if "transaction" in kwargs: - logger.warning(deprecation_msg) - name = kwargs.pop("transaction") - return self.start_transaction(name=name, **kwargs) + if isinstance(span, Transaction): + logger.warning(deprecation_msg) + return self.start_transaction(span) + if "transaction" in kwargs: + logger.warning(deprecation_msg) + name = kwargs.pop("transaction") + return self.start_transaction(name=name, **kwargs) if span is not None: return span @@ -700,8 +695,7 @@ def iter_trace_propagation_headers(self, span=None): if not propagate_traces: return - for header in span.iter_headers(): - yield header + yield from span.iter_headers() GLOBAL_HUB = Hub() diff --git a/sentry_sdk/integrations/__init__.py b/sentry_sdk/integrations/__init__.py index 777c363e14..120ca0e086 100644 --- a/sentry_sdk/integrations/__init__.py +++ b/sentry_sdk/integrations/__init__.py @@ -92,9 +92,11 @@ def setup_integrations( `with_defaults` is set to `True` then all default integrations are added unless they were already provided before. """ - integrations = dict( - (integration.identifier, integration) for integration in integrations or () - ) + integrations = { + integration.identifier: integration + for integration in integrations or () + } + logger.debug("Setting up integrations (with default = %s)", with_defaults) @@ -119,15 +121,14 @@ def setup_integrations( try: type(integration).setup_once() except NotImplementedError: - if getattr(integration, "install", None) is not None: - logger.warning( - "Integration %s: The install method is " - "deprecated. Use `setup_once`.", - identifier, - ) - integration.install() - else: + if getattr(integration, "install", None) is None: raise + logger.warning( + "Integration %s: The install method is " + "deprecated. Use `setup_once`.", + identifier, + ) + integration.install() except DidNotEnable as e: if identifier not in used_as_default_integration: raise diff --git a/sentry_sdk/integrations/asgi.py b/sentry_sdk/integrations/asgi.py index f73b856730..4c7492eab2 100644 --- a/sentry_sdk/integrations/asgi.py +++ b/sentry_sdk/integrations/asgi.py @@ -88,10 +88,7 @@ def __init__(self, app, unsafe_context_data=False): ) self.app = app - if _looks_like_asgi3(app): - self.__call__ = self._run_asgi3 # type: Callable[..., Any] - else: - self.__call__ = self._run_asgi2 + self.__call__ = self._run_asgi3 if _looks_like_asgi3(app) else self._run_asgi2 def _run_asgi2(self, scope): # type: (Any) -> Any @@ -252,8 +249,5 @@ def _get_headers(self, scope): for raw_key, raw_value in scope["headers"]: key = raw_key.decode("latin-1") value = raw_value.decode("latin-1") - if key in headers: - headers[key] = headers[key] + ", " + value - else: - headers[key] = value + headers[key] = headers[key] + ", " + value if key in headers else value return headers diff --git a/sentry_sdk/integrations/aws_lambda.py b/sentry_sdk/integrations/aws_lambda.py index 533250efaa..2c62d81086 100644 --- a/sentry_sdk/integrations/aws_lambda.py +++ b/sentry_sdk/integrations/aws_lambda.py @@ -360,11 +360,10 @@ def event_processor(sentry_event, hint, start_time=start_time): if "body" in aws_event: request["data"] = aws_event.get("body", "") - else: - if aws_event.get("body", None): - # Unfortunately couldn't find a way to get structured body from AWS - # event. Meaning every body is unstructured to us. - request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]}) + elif aws_event.get("body", None): + # Unfortunately couldn't find a way to get structured body from AWS + # event. Meaning every body is unstructured to us. + request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]}) sentry_event["request"] = request @@ -402,7 +401,7 @@ def _get_cloudwatch_logs_url(aws_context, start_time): formatstring = "%Y-%m-%dT%H:%M:%SZ" region = environ.get("AWS_REGION", "") - url = ( + return ( "https://console.{domain}/cloudwatch/home?region={region}" "#logEventViewer:group={log_group};stream={log_stream}" ";start={start_time};end={end_time}" @@ -414,5 +413,3 @@ def _get_cloudwatch_logs_url(aws_context, start_time): start_time=(start_time - timedelta(seconds=1)).strftime(formatstring), end_time=(datetime.utcnow() + timedelta(seconds=2)).strftime(formatstring), ) - - return url diff --git a/sentry_sdk/integrations/celery.py b/sentry_sdk/integrations/celery.py index 9ba458a387..e947c85b70 100644 --- a/sentry_sdk/integrations/celery.py +++ b/sentry_sdk/integrations/celery.py @@ -95,27 +95,26 @@ def apply_async(*args, **kwargs): # type: (*Any, **Any) -> Any hub = Hub.current integration = hub.get_integration(CeleryIntegration) - if integration is not None and integration.propagate_traces: - with hub.start_span(op="celery.submit", description=args[0].name) as span: - with capture_internal_exceptions(): - headers = dict(hub.iter_trace_propagation_headers(span)) - - if headers: - # Note: kwargs can contain headers=None, so no setdefault! - # Unsure which backend though. - kwarg_headers = kwargs.get("headers") or {} - kwarg_headers.update(headers) - - # https://github.com/celery/celery/issues/4875 - # - # Need to setdefault the inner headers too since other - # tracing tools (dd-trace-py) also employ this exact - # workaround and we don't want to break them. - kwarg_headers.setdefault("headers", {}).update(headers) - kwargs["headers"] = kwarg_headers + if integration is None or not integration.propagate_traces: + return f(*args, **kwargs) + with hub.start_span(op="celery.submit", description=args[0].name) as span: + with capture_internal_exceptions(): + headers = dict(hub.iter_trace_propagation_headers(span)) + + if headers: + # Note: kwargs can contain headers=None, so no setdefault! + # Unsure which backend though. + kwarg_headers = kwargs.get("headers") or {} + kwarg_headers.update(headers) + + # https://github.com/celery/celery/issues/4875 + # + # Need to setdefault the inner headers too since other + # tracing tools (dd-trace-py) also employ this exact + # workaround and we don't want to break them. + kwarg_headers.setdefault("headers", {}).update(headers) + kwargs["headers"] = kwarg_headers - return f(*args, **kwargs) - else: return f(*args, **kwargs) return apply_async # type: ignore diff --git a/sentry_sdk/integrations/django/__init__.py b/sentry_sdk/integrations/django/__init__.py index 87f9c7bc61..fbce1ea18f 100644 --- a/sentry_sdk/integrations/django/__init__.py +++ b/sentry_sdk/integrations/django/__init__.py @@ -266,7 +266,6 @@ def sentry_patched_drf_initial(self, request, *args, **kwargs): request._request._sentry_drf_request_backref = weakref.ref( request ) - pass return old_drf_initial(self, request, *args, **kwargs) APIView.initial = sentry_patched_drf_initial diff --git a/sentry_sdk/integrations/django/templates.py b/sentry_sdk/integrations/django/templates.py index 2ff9d1b184..cc9d567414 100644 --- a/sentry_sdk/integrations/django/templates.py +++ b/sentry_sdk/integrations/django/templates.py @@ -43,12 +43,10 @@ def get_template_frame_from_exception(exc_value): def _get_template_name_description(template_name): - # type: (str) -> str - if isinstance(template_name, (list, tuple)): - if template_name: - return "[{}, ...]".format(template_name[0]) - else: + if not isinstance(template_name, (list, tuple)): return template_name + if template_name: + return "[{}, ...]".format(template_name[0]) def patch_templates(): diff --git a/sentry_sdk/integrations/falcon.py b/sentry_sdk/integrations/falcon.py index f794216140..88883e0fbf 100644 --- a/sentry_sdk/integrations/falcon.py +++ b/sentry_sdk/integrations/falcon.py @@ -143,11 +143,7 @@ def sentry_patched_handle_exception(self, *args): # NOTE(jmagnusson): falcon 2.0 changed falcon.API._handle_exception # method signature from `(ex, req, resp, params)` to # `(req, resp, ex, params)` - if isinstance(args[0], Exception): - ex = args[0] - else: - ex = args[2] - + ex = args[0] if isinstance(args[0], Exception) else args[2] was_handled = original_handle_exception(self, *args) hub = Hub.current diff --git a/sentry_sdk/integrations/gcp.py b/sentry_sdk/integrations/gcp.py index e92422d8b9..001269e474 100644 --- a/sentry_sdk/integrations/gcp.py +++ b/sentry_sdk/integrations/gcp.py @@ -77,9 +77,7 @@ def sentry_func(functionhandler, gcp_event, *args, **kwargs): # Starting the thread to raise timeout warning exception timeout_thread.start() - headers = {} - if hasattr(gcp_event, "headers"): - headers = gcp_event.headers + headers = gcp_event.headers if hasattr(gcp_event, "headers") else {} transaction = Transaction.continue_from_headers( headers, op="serverless.function", name=environ.get("FUNCTION_NAME", "") ) @@ -183,11 +181,10 @@ def event_processor(event, hint): if _should_send_default_pii(): if hasattr(gcp_event, "data"): request["data"] = gcp_event.data - else: - if hasattr(gcp_event, "data"): - # Unfortunately couldn't find a way to get structured body from GCP - # event. Meaning every body is unstructured to us. - request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]}) + elif hasattr(gcp_event, "data"): + # Unfortunately couldn't find a way to get structured body from GCP + # event. Meaning every body is unstructured to us. + request["data"] = AnnotatedValue("", {"rem": [["!raw", "x", 0, 0]]}) event["request"] = request @@ -208,7 +205,7 @@ def _get_google_cloud_logs_url(final_time): hour_ago = final_time - timedelta(hours=1) formatstring = "%Y-%m-%dT%H:%M:%SZ" - url = ( + return ( "https://console.cloud.google.com/logs/viewer?project={project}&resource=cloud_function" "%2Ffunction_name%2F{function_name}%2Fregion%2F{region}&minLogLevel=0&expandAll=false" "×tamp={timestamp_end}&customFacets=&limitCustomFacetWidth=true" @@ -221,5 +218,3 @@ def _get_google_cloud_logs_url(final_time): timestamp_end=final_time.strftime(formatstring), timestamp_start=hour_ago.strftime(formatstring), ) - - return url diff --git a/sentry_sdk/integrations/logging.py b/sentry_sdk/integrations/logging.py index 80524dbab2..fd30a6f822 100644 --- a/sentry_sdk/integrations/logging.py +++ b/sentry_sdk/integrations/logging.py @@ -100,10 +100,7 @@ def sentry_patched_callhandlers(self, record): def _can_record(record): # type: (LogRecord) -> bool """Prevents ignored loggers from recording""" - for logger in _IGNORED_LOGGERS: - if fnmatch(record.name, logger): - return False - return True + return not any(fnmatch(record.name, logger) for logger in _IGNORED_LOGGERS) def _breadcrumb_from_record(record): @@ -199,7 +196,7 @@ def _emit(self, record): client_options=client_options, mechanism={"type": "logging", "handled": True}, ) - elif record.exc_info and record.exc_info[0] is None: + elif record.exc_info: event = {} hint = {} with capture_internal_exceptions(): diff --git a/sentry_sdk/integrations/spark/spark_worker.py b/sentry_sdk/integrations/spark/spark_worker.py index 2c27647dab..9f106e0b7f 100644 --- a/sentry_sdk/integrations/spark/spark_worker.py +++ b/sentry_sdk/integrations/spark/spark_worker.py @@ -44,16 +44,14 @@ def _capture_exception(exc_info, hub): exc_info = exc_info_from_error(exc_info) exc_type, exc_value, tb = exc_info - rv = [] - - # On Exception worker will call sys.exit(-1), so we can ignore SystemExit and similar errors - for exc_type, exc_value, tb in walk_exception_chain(exc_info): - if exc_type not in (SystemExit, EOFError, ConnectionResetError): - rv.append( - single_exception_from_error_tuple( - exc_type, exc_value, tb, client_options, mechanism - ) - ) + rv = [ + single_exception_from_error_tuple( + exc_type, exc_value, tb, client_options, mechanism + ) + for exc_type, exc_value, tb in walk_exception_chain(exc_info) + if exc_type not in (SystemExit, EOFError, ConnectionResetError) + ] + if rv: rv.reverse() diff --git a/sentry_sdk/integrations/threading.py b/sentry_sdk/integrations/threading.py index b750257e2a..a10c294b19 100644 --- a/sentry_sdk/integrations/threading.py +++ b/sentry_sdk/integrations/threading.py @@ -37,10 +37,7 @@ def sentry_start(self, *a, **kw): hub = Hub.current integration = hub.get_integration(ThreadingIntegration) if integration is not None: - if not integration.propagate_hub: - hub_ = None - else: - hub_ = Hub(hub) + hub_ = None if not integration.propagate_hub else Hub(hub) # Patching instance methods in `start()` creates a reference cycle if # done in a naive way. See # https://github.com/getsentry/sentry-python/pull/434 diff --git a/sentry_sdk/integrations/tornado.py b/sentry_sdk/integrations/tornado.py index f9796daca3..62e76c2ecd 100644 --- a/sentry_sdk/integrations/tornado.py +++ b/sentry_sdk/integrations/tornado.py @@ -76,8 +76,7 @@ async def sentry_execute_request_handler(self, *args, **kwargs): def sentry_execute_request_handler(self, *args, **kwargs): # type: ignore # type: (RequestHandler, *Any, **Any) -> Any with _handle_request_impl(self): - result = yield from old_execute(self, *args, **kwargs) - return result + return (yield from old_execute(self, *args, **kwargs)) RequestHandler._execute = sentry_execute_request_handler # type: ignore diff --git a/sentry_sdk/integrations/wsgi.py b/sentry_sdk/integrations/wsgi.py index 4f274fa00c..79ce89fde4 100644 --- a/sentry_sdk/integrations/wsgi.py +++ b/sentry_sdk/integrations/wsgi.py @@ -199,7 +199,7 @@ def _get_headers(environ): "HTTP_CONTENT_LENGTH", ): yield key[5:].replace("_", "-").title(), value - elif key in ("CONTENT_TYPE", "CONTENT_LENGTH"): + elif key in {"CONTENT_TYPE", "CONTENT_LENGTH"}: yield key.replace("_", "-").title(), value diff --git a/sentry_sdk/serializer.py b/sentry_sdk/serializer.py index 4dc4bb5177..28ef92498d 100644 --- a/sentry_sdk/serializer.py +++ b/sentry_sdk/serializer.py @@ -99,9 +99,8 @@ def __enter__(self): obj = self._objs[-1] if id(obj) in self._ids: return True - else: - self._ids[id(obj)] = obj - return False + self._ids[id(obj)] = obj + return False def __exit__( self, diff --git a/sentry_sdk/utils.py b/sentry_sdk/utils.py index 8fb03e014d..741f6b13f9 100644 --- a/sentry_sdk/utils.py +++ b/sentry_sdk/utils.py @@ -172,7 +172,7 @@ def __init__(self, value): self.host = parts.hostname if parts.port is None: - self.port = self.scheme == "https" and 443 or 80 + self.port = 443 if self.scheme == "https" else 80 else: self.port = parts.port @@ -539,22 +539,14 @@ def single_exception_from_error_tuple( mechanism=None, # type: Optional[Dict[str, Any]] ): # type: (...) -> Dict[str, Any] - if exc_value is not None: - errno = get_errno(exc_value) - else: - errno = None - + errno = get_errno(exc_value) if exc_value is not None else None if errno is not None: mechanism = mechanism or {"type": "generic"} mechanism.setdefault("meta", {}).setdefault("errno", {}).setdefault( "number", errno ) - if client_options is None: - with_locals = True - else: - with_locals = client_options["with_locals"] - + with_locals = True if client_options is None else client_options["with_locals"] frames = [ serialize_frame(tb.tb_frame, tb_lineno=tb.tb_lineno, with_locals=with_locals) for tb in iter_stacks(tb) @@ -622,14 +614,9 @@ def exceptions_from_error_tuple( ): # type: (...) -> List[Dict[str, Any]] exc_type, exc_value, tb = exc_info - rv = [] - for exc_type, exc_value, tb in walk_exception_chain(exc_info): - rv.append( - single_exception_from_error_tuple( + rv = [single_exception_from_error_tuple( exc_type, exc_value, tb, client_options, mechanism - ) - ) - + ) for exc_type, exc_value, tb in walk_exception_chain(exc_info)] rv.reverse() return rv @@ -660,8 +647,7 @@ def iter_event_stacktraces(event): def iter_event_frames(event): # type: (Dict[str, Any]) -> Iterator[Dict[str, Any]] for stacktrace in iter_event_stacktraces(event): - for frame in stacktrace.get("frames") or (): - yield frame + yield from stacktrace.get("frames") or () def handle_in_app(event, in_app_exclude=None, in_app_include=None): @@ -753,10 +739,7 @@ def _module_in_set(name, set): # type: (str, Optional[List[str]]) -> bool if not set: return False - for item in set or (): - if item == name or name.startswith(item + "."): - return True - return False + return any(item == name or name.startswith(item + ".") for item in set or ()) def strip_string(value, max_length=None): @@ -792,7 +775,7 @@ def _is_contextvars_broken(): from gevent.monkey import is_object_patched # type: ignore # Get the MAJOR and MINOR version numbers of Gevent - version_tuple = tuple([int(part) for part in gevent.__version__.split(".")[:2]]) + version_tuple = tuple(int(part) for part in gevent.__version__.split(".")[:2]) if is_object_patched("threading", "local"): # Gevent 20.9.0 depends on Greenlet 0.4.17 which natively handles switching # context vars when greenlets are switched, so, Gevent 20.9.0+ is all fine. @@ -800,15 +783,10 @@ def _is_contextvars_broken(): # Gevent 20.5, that doesn't depend on Greenlet 0.4.17 with native support # for contextvars, is able to patch both thread locals and contextvars, in # that case, check if contextvars are effectively patched. - if ( - # Gevent 20.9.0+ - (sys.version_info >= (3, 7) and version_tuple >= (20, 9)) - # Gevent 20.5.0+ or Python < 3.7 - or (is_object_patched("contextvars", "ContextVar")) - ): - return False + return ( + sys.version_info < (3, 7) or version_tuple < (20, 9) + ) and not (is_object_patched("contextvars", "ContextVar")) - return True except ImportError: pass @@ -853,28 +831,18 @@ def _get_contextvars(): See https://docs.sentry.io/platforms/python/contextvars/ for more information. """ if not _is_contextvars_broken(): - # aiocontextvars is a PyPI package that ensures that the contextvars - # backport (also a PyPI package) works with asyncio under Python 3.6 - # - # Import it if available. - if sys.version_info < (3, 7): # `aiocontextvars` is absolutely required for functional # contextvars on Python 3.6. - try: + try: + if sys.version_info < (3, 7): from aiocontextvars import ContextVar # noqa - return True, ContextVar - except ImportError: - pass - else: - # On Python 3.7 contextvars are functional. - try: + else: from contextvars import ContextVar - return True, ContextVar - except ImportError: - pass - + return True, ContextVar + except ImportError: + pass # Fall back to basic thread-local usage. from threading import local @@ -963,7 +931,7 @@ def run(self): # Setting up the exact integer value of configured time(in seconds) if integer_configured_timeout < self.configured_timeout: - integer_configured_timeout = integer_configured_timeout + 1 + integer_configured_timeout += 1 # Raising Exception after timeout duration is reached raise ServerlessTimeoutWarning( diff --git a/tests/conftest.py b/tests/conftest.py index 1df4416f7f..216b26c3b8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -146,8 +146,8 @@ def check_envelope(envelope): # Assert error events are sent without envelope to server, for compat. # This does not apply if any item in the envelope is an attachment. if not any(x.type == "attachment" for x in envelope.items): - assert not any(item.data_category == "error" for item in envelope.items) - assert not any(item.get_event() is not None for item in envelope.items) + assert all(item.data_category != "error" for item in envelope.items) + assert all(item.get_event() is None for item in envelope.items) def inner(client): monkeypatch.setattr( @@ -504,9 +504,8 @@ def __init__(self, type=None, attrs=None): self.attrs = attrs def __eq__(self, test_obj): - if self.type: - if not isinstance(test_obj, self.type): - return False + if self.type and not isinstance(test_obj, self.type): + return False if self.attrs: for attr_name, attr_value in self.attrs.items(): diff --git a/tests/integrations/conftest.py b/tests/integrations/conftest.py index cffb278d70..a6acb29e26 100644 --- a/tests/integrations/conftest.py +++ b/tests/integrations/conftest.py @@ -9,10 +9,9 @@ def inner(): old_capture_event = sentry_sdk.Hub.capture_event def capture_event(self, event, hint=None): - if hint: - if "exc_info" in hint: - error = hint["exc_info"][1] - errors.add(error) + if hint and "exc_info" in hint: + error = hint["exc_info"][1] + errors.add(error) return old_capture_event(self, event, hint=hint) monkeypatch.setattr(sentry_sdk.Hub, "capture_event", capture_event) diff --git a/tests/integrations/django/myapp/middleware.py b/tests/integrations/django/myapp/middleware.py index b4c1145390..1caad5fe8e 100644 --- a/tests/integrations/django/myapp/middleware.py +++ b/tests/integrations/django/myapp/middleware.py @@ -13,7 +13,6 @@ async def middleware(request): else: def middleware(request): - response = get_response(request) - return response + return get_response(request) return middleware diff --git a/tests/integrations/logging/test_logging.py b/tests/integrations/logging/test_logging.py index 22ea14f8ae..6a2257eea3 100644 --- a/tests/integrations/logging/test_logging.py +++ b/tests/integrations/logging/test_logging.py @@ -43,9 +43,10 @@ def test_logging_defaults(integrations, sentry_init, capture_events, kwargs): assert event["level"] == "fatal" assert any(crumb["message"] == "bread" for crumb in event["breadcrumbs"]["values"]) - assert not any( - crumb["message"] == "LOL" for crumb in event["breadcrumbs"]["values"] + assert all( + crumb["message"] != "LOL" for crumb in event["breadcrumbs"]["values"] ) + assert "threads" not in event diff --git a/tests/integrations/spark/test_spark.py b/tests/integrations/spark/test_spark.py index 00c0055f12..06725329dd 100644 --- a/tests/integrations/spark/test_spark.py +++ b/tests/integrations/spark/test_spark.py @@ -92,8 +92,7 @@ def jobId(self): # noqa: N802 return "sample-job-id-end" def jobResult(self): # noqa: N802 - result = MockJobResult() - return result + return MockJobResult() mock_job_end = MockJobEnd() listener.onJobEnd(mock_job_end) @@ -118,8 +117,7 @@ def attemptId(self): # noqa: N802 class MockStageSubmitted: def stageInfo(self): # noqa: N802 - stageinf = StageInfo() - return stageinf + return StageInfo() mock_stage_submitted = MockStageSubmitted() listener.onStageSubmitted(mock_stage_submitted) diff --git a/tests/integrations/tornado/test_tornado.py b/tests/integrations/tornado/test_tornado.py index 1c5137f2b2..c8386a574c 100644 --- a/tests/integrations/tornado/test_tornado.py +++ b/tests/integrations/tornado/test_tornado.py @@ -77,7 +77,7 @@ def test_basic(tornado_testcase, sentry_init, capture_events): request = event["request"] host = request["headers"]["Host"] - assert event["request"] == { + assert request == { "env": {"REMOTE_ADDR": "127.0.0.1"}, "headers": { "Accept-Encoding": "gzip", @@ -90,7 +90,6 @@ def test_basic(tornado_testcase, sentry_init, capture_events): "query_string": "foo=bar", "url": "http://{host}/hi".format(host=host), } - assert event["tags"] == {"foo": "42"} assert ( event["transaction"] @@ -152,7 +151,7 @@ def test_transactions(tornado_testcase, sentry_init, capture_events, handler, co request = server_tx["request"] host = request["headers"]["Host"] - assert server_tx["request"] == { + assert request == { "env": {"REMOTE_ADDR": "127.0.0.1"}, "headers": { "Accept-Encoding": "gzip", @@ -164,7 +163,6 @@ def test_transactions(tornado_testcase, sentry_init, capture_events, handler, co "data": {"heyoo": [""]}, "url": "http://{host}/hi".format(host=host), } - assert ( client_tx["contexts"]["trace"]["trace_id"] == server_tx["contexts"]["trace"]["trace_id"] diff --git a/tests/integrations/trytond/test_trytond.py b/tests/integrations/trytond/test_trytond.py index 055f7926eb..9f2f8223b9 100644 --- a/tests/integrations/trytond/test_trytond.py +++ b/tests/integrations/trytond/test_trytond.py @@ -97,10 +97,9 @@ def _(request): def _(app, request, e): if isinstance(e, TrytondBaseException): return - else: - event_id = last_event_id() - data = TrytondUserError(str(event_id), str(e)) - return app.make_response(request, data) + event_id = last_event_id() + data = TrytondUserError(str(event_id), str(e)) + return app.make_response(request, data) client = get_client() diff --git a/tests/tracing/test_integration_tests.py b/tests/tracing/test_integration_tests.py index f9530d31b3..aebf227961 100644 --- a/tests/tracing/test_integration_tests.py +++ b/tests/tracing/test_integration_tests.py @@ -90,11 +90,9 @@ def test_continue_from_headers(sentry_init, capture_events, sampled, sample_rate if sampled is False or (sample_rate == 0 and sampled is None): trace1, message = events - assert trace1["transaction"] == "hi" else: trace1, message, trace2 = events - assert trace1["transaction"] == "hi" assert trace2["transaction"] == "ho" assert ( @@ -104,6 +102,7 @@ def test_continue_from_headers(sentry_init, capture_events, sampled, sample_rate == message["contexts"]["trace"]["trace_id"] ) + assert trace1["transaction"] == "hi" assert message["message"] == "hello"