Skip to content
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
23 changes: 8 additions & 15 deletions scripts/build_aws_lambda_layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,10 @@
import subprocess
import sys
import tempfile
from typing import TYPE_CHECKING
from typing import Optional

from sentry_sdk.consts import VERSION as SDK_VERSION

if TYPE_CHECKING:
from typing import Optional

DIST_PATH = "dist" # created by "make dist" that is called by "make aws-lambda-layer"
PYTHON_SITE_PACKAGES = "python" # see https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path
Expand All @@ -17,10 +15,9 @@
class LayerBuilder:
def __init__(
self,
base_dir, # type: str
out_zip_filename=None, # type: Optional[str]
):
# type: (...) -> None
base_dir: str,
out_zip_filename: Optional[str] = None,
) -> None:
self.base_dir = base_dir
self.python_site_packages = os.path.join(self.base_dir, PYTHON_SITE_PACKAGES)
self.out_zip_filename = (
Expand All @@ -29,12 +26,10 @@ def __init__(
else out_zip_filename
)

def make_directories(self):
# type: (...) -> None
def make_directories(self) -> None:
os.makedirs(self.python_site_packages)

def install_python_packages(self):
# type: (...) -> None
def install_python_packages(self) -> None:
# Install requirements for Lambda Layer (these are more limited than the SDK requirements,
# because Lambda does not support the newest versions of some packages)
subprocess.check_call(
Expand Down Expand Up @@ -68,8 +63,7 @@ def install_python_packages(self):
check=True,
)

def create_init_serverless_sdk_package(self):
# type: (...) -> None
def create_init_serverless_sdk_package(self) -> None:
"""
Method that creates the init_serverless_sdk pkg in the
sentry-python-serverless zip
Expand All @@ -84,8 +78,7 @@ def create_init_serverless_sdk_package(self):
"scripts/init_serverless_sdk.py", f"{serverless_sdk_path}/__init__.py"
)

def zip(self):
# type: (...) -> None
def zip(self) -> None:
subprocess.run(
[
"zip",
Expand Down
9 changes: 2 additions & 7 deletions scripts/init_serverless_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,11 @@
import os
import sys
import re
from typing import Any

import sentry_sdk
from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from typing import Any


# Configure Sentry SDK
sentry_sdk.init(
Expand Down Expand Up @@ -70,8 +66,7 @@ def get_lambda_handler(self):
return getattr(self.lambda_function_module, self.handler_name)


def sentry_lambda_handler(event, context):
# type: (Any, Any) -> None
def sentry_lambda_handler(event: Any, context: Any) -> None:
"""
Handler function that invokes a lambda handler which path is defined in
environment variables as "SENTRY_INITIAL_HANDLER"
Expand Down
3 changes: 1 addition & 2 deletions sentry_sdk/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,5 @@ def end_session() -> None:


@scopemethod
def set_transaction_name(name, source=None):
# type: (str, Optional[str]) -> None
def set_transaction_name(name: str, source: Optional[str] = None) -> None:
return get_current_scope().set_transaction_name(name, source)
3 changes: 1 addition & 2 deletions sentry_sdk/integrations/django/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -712,8 +712,7 @@ def _set_db_data(span: Span, cursor_or_db: Any) -> None:
span.set_attribute(SPANDATA.SERVER_SOCKET_ADDRESS, server_socket_address)


def add_template_context_repr_sequence():
# type: () -> None
def add_template_context_repr_sequence() -> None:
try:
from django.template.context import BaseContext

Expand Down
5 changes: 2 additions & 3 deletions sentry_sdk/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,10 @@ def add_global_repr_processor(processor: ReprProcessor) -> None:
global_repr_processors.append(processor)


sequence_types = [Sequence, Set] # type: List[type]
sequence_types: list[type] = [Sequence, Set]


def add_repr_sequence_type(ty):
# type: (type) -> None
def add_repr_sequence_type(ty: type) -> None:
sequence_types.append(ty)


Expand Down
8 changes: 4 additions & 4 deletions sentry_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1875,12 +1875,12 @@ def set_thread_info_from_span(
data[SPANDATA.THREAD_NAME] = span.get_attribute(SPANDATA.THREAD_NAME)


def safe_serialize(data):
# type: (Any) -> str
def safe_serialize(data: Any) -> str:
"""Safely serialize to a readable string."""

def serialize_item(item):
# type: (Any) -> Union[str, dict[Any, Any], list[Any], tuple[Any, ...]]
def serialize_item(
item: Any,
) -> Union[str, dict[Any, Any], list[Any], tuple[Any, ...]]:
if callable(item):
try:
module = getattr(item, "__module__", None)
Expand Down
3 changes: 1 addition & 2 deletions tests/integrations/chalice/test_chalice.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,10 @@
from pytest_chalice.handlers import RequestHandler


def _generate_lambda_context(self):
def _generate_lambda_context(self) -> LambdaContext:
# Monkeypatch of the function _generate_lambda_context
# from the class LocalGateway
# for mock the timeout
# type: () -> LambdaContext
if self._config.lambda_timeout is None:
timeout = 10 * 1000
else:
Expand Down
3 changes: 1 addition & 2 deletions tests/integrations/django/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
from sentry_sdk.integrations.django.middleware import _wrap_middleware


def _sync_capable_middleware_factory(sync_capable):
# type: (Optional[bool]) -> type
def _sync_capable_middleware_factory(sync_capable: Optional[bool]) -> type:
"""Create a middleware class with a sync_capable attribute set to the value passed to the factory.
If the factory is called with None, the middleware class will not have a sync_capable attribute.
"""
Expand Down
4 changes: 2 additions & 2 deletions tests/integrations/langchain/test_langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ def get_word_length(word: str) -> int:
return len(word)


global stream_result_mock # type: Mock
global llm_type # type: str
stream_result_mock: Mock
llm_type: str


class MockOpenAI(ChatOpenAI):
Expand Down
26 changes: 11 additions & 15 deletions tests/integrations/sanic/test_sanic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import os
import random
import sys
from typing import Any, Iterable, Optional, Container
from unittest.mock import Mock

import pytest
Expand All @@ -26,11 +27,6 @@
except ImportError:
ReusableClient = None

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from collections.abc import Iterable, Container
from typing import Any, Optional

SANIC_VERSION = tuple(map(int, SANIC_VERSION_RAW.split(".")))
PERFORMANCE_SUPPORTED = SANIC_VERSION >= (21, 9)
Expand Down Expand Up @@ -341,14 +337,13 @@ class TransactionTestConfig:

def __init__(
self,
integration_args,
url,
expected_status,
expected_transaction_name,
expected_source=None,
has_transaction_event=True,
):
# type: (Iterable[Optional[Container[int]]], str, int, Optional[str], Optional[str], bool) -> None
integration_args: Iterable[Optional[Container[int]]],
url: str,
expected_status: int,
expected_transaction_name: Optional[str],
expected_source: Optional[str] = None,
has_transaction_event: bool = True,
) -> None:
"""
expected_transaction_name of None indicates we expect to not receive a transaction
"""
Expand Down Expand Up @@ -408,8 +403,9 @@ def __init__(
),
],
)
def test_transactions(test_config, sentry_init, app, capture_events):
# type: (TransactionTestConfig, Any, Any, Any) -> None
def test_transactions(
test_config: TransactionTestConfig, sentry_init: Any, app: Any, capture_events: Any
) -> None:

# Init the SanicIntegration with the desired arguments
sentry_init(
Expand Down
9 changes: 3 additions & 6 deletions tests/profiler/test_transaction_profiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -623,16 +623,13 @@ def test_max_profile_duration_reached(scheduler_class):


class NoopScheduler(Scheduler):
def setup(self):
# type: () -> None
def setup(self) -> None:
pass

def teardown(self):
# type: () -> None
def teardown(self) -> None:
pass

def ensure_running(self):
# type: () -> None
def ensure_running(self) -> None:
pass


Expand Down
4 changes: 2 additions & 2 deletions tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ class NoOpIntegration(Integration):
identifier = "noop"

@staticmethod
def setup_once(): # type: () -> None
def setup_once() -> None:
pass

def __eq__(self, __value): # type: (object) -> bool
def __eq__(self, __value: object) -> bool:
"""
All instances of NoOpIntegration should be considered equal to each other.
"""
Expand Down
27 changes: 9 additions & 18 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
import sys
import time
from collections import Counter, defaultdict
from collections.abc import Mapping
from textwrap import dedent
from unittest import mock
from typing import Optional, Union, Mapping, Callable

import pytest

Expand All @@ -26,13 +26,7 @@
from sentry_sdk.transport import Transport
from sentry_sdk.serializer import MAX_DATABAG_BREADTH
from sentry_sdk.consts import DEFAULT_MAX_BREADCRUMBS, DEFAULT_MAX_VALUE_LENGTH

from typing import TYPE_CHECKING

if TYPE_CHECKING:
from collections.abc import Callable
from typing import Any, Optional, Union
from sentry_sdk._types import Event
from sentry_sdk.types import Event


maximum_python_312 = pytest.mark.skipif(
Expand Down Expand Up @@ -1135,12 +1129,11 @@ def test_spotlight_option(
class IssuesSamplerTestConfig:
def __init__(
self,
expected_events,
sampler_function=None,
sample_rate=None,
exception_to_raise=Exception,
):
# type: (int, Optional[Callable[[Event], Union[float, bool]]], Optional[float], type[Exception]) -> None
expected_events: int,
sampler_function: Optional[Callable[[Event], Union[float, bool]]] = None,
sample_rate: Optional[float] = None,
exception_to_raise: type = Exception,
) -> None:
self.sampler_function_mock = (
None
if sampler_function is None
Expand All @@ -1150,14 +1143,12 @@ def __init__(
self.sample_rate = sample_rate
self.exception_to_raise = exception_to_raise

def init_sdk(self, sentry_init):
# type: (Callable[[*Any], None]) -> None
def init_sdk(self, sentry_init: Callable[..., None]) -> None:
sentry_init(
error_sampler=self.sampler_function_mock, sample_rate=self.sample_rate
)

def raise_exception(self):
# type: () -> None
def raise_exception(self) -> None:
raise self.exception_to_raise()


Expand Down
10 changes: 4 additions & 6 deletions tests/test_logs.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,8 @@
)


def otel_attributes_to_dict(otel_attrs):
# type: (Mapping[str, Any]) -> Mapping[str, Any]
def _convert_attr(attr):
# type: (Mapping[str, Union[str, float, bool]]) -> Any
def otel_attributes_to_dict(otel_attrs: Mapping[str, Any]) -> Mapping[str, Any]:
def _convert_attr(attr: Mapping[str, Union[str, float, bool]]) -> Any:
if attr["type"] == "boolean":
return attr["value"]
if attr["type"] == "double":
Expand All @@ -38,7 +36,7 @@ def _convert_attr(attr):


def envelopes_to_logs(envelopes: List[Envelope]) -> List[Log]:
res = [] # type: List[Log]
res: List[Log] = []
for envelope in envelopes:
for item in envelope.items:
if item.type == "log":
Expand All @@ -54,7 +52,7 @@ def envelopes_to_logs(envelopes: List[Envelope]) -> List[Log]:
"attributes": otel_attributes_to_dict(log_json["attributes"]),
"time_unix_nano": int(float(log_json["timestamp"]) * 1e9),
"trace_id": log_json["trace_id"],
} # type: Log
}
res.append(log)
return res

Expand Down
8 changes: 4 additions & 4 deletions tests/test_tracing_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
import pytest


def id_function(val):
# type: (object) -> str
def id_function(val: object) -> str:
if isinstance(val, ShouldBeIncludedTestCase):
return val.id

Expand Down Expand Up @@ -88,8 +87,9 @@ class ShouldBeIncludedTestCase:
],
ids=id_function,
)
def test_should_be_included(test_case, expected):
# type: (ShouldBeIncludedTestCase, bool) -> None
def test_should_be_included(
test_case: ShouldBeIncludedTestCase, expected: bool
) -> None:
"""Checking logic, see: https://github.com/getsentry/sentry-python/issues/3312"""
kwargs = asdict(test_case)
kwargs.pop("id")
Expand Down
3 changes: 1 addition & 2 deletions tests/test_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,7 @@ def inner(**kwargs):
return inner


def mock_transaction_envelope(span_count):
# type: (int) -> Envelope
def mock_transaction_envelope(span_count: int) -> Envelope:
event = defaultdict(
mock.MagicMock,
type="transaction",
Expand Down
3 changes: 1 addition & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,7 @@ class TestIntegration(Integration):
gevent = None


def _normalize_distribution_name(name):
# type: (str) -> str
def _normalize_distribution_name(name: str) -> str:
"""Normalize distribution name according to PEP-0503.

See:
Expand Down
Loading