diff --git a/sentry_sdk/integrations/_asgi_common.py b/sentry_sdk/integrations/_asgi_common.py index 17a88523e5..a099b42e32 100644 --- a/sentry_sdk/integrations/_asgi_common.py +++ b/sentry_sdk/integrations/_asgi_common.py @@ -1,6 +1,6 @@ import urllib -from sentry_sdk.hub import _should_send_default_pii +from sentry_sdk.scope import should_send_default_pii from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk._types import TYPE_CHECKING @@ -101,7 +101,7 @@ def _get_request_data(asgi_scope): ) client = asgi_scope.get("client") - if client and _should_send_default_pii(): + if client and should_send_default_pii(): request_data["env"] = {"REMOTE_ADDR": _get_ip(asgi_scope)} return request_data diff --git a/sentry_sdk/integrations/gnu_backtrace.py b/sentry_sdk/integrations/gnu_backtrace.py index f8321a6cd7..32d2afafbf 100644 --- a/sentry_sdk/integrations/gnu_backtrace.py +++ b/sentry_sdk/integrations/gnu_backtrace.py @@ -1,6 +1,6 @@ import re -from sentry_sdk.hub import Hub +import sentry_sdk from sentry_sdk.integrations import Integration from sentry_sdk.scope import add_global_event_processor from sentry_sdk.utils import capture_internal_exceptions @@ -49,7 +49,7 @@ def process_gnu_backtrace(event, hint): def _process_gnu_backtrace(event, hint): # type: (Event, dict[str, Any]) -> Event - if Hub.current.get_integration(GnuBacktraceIntegration) is None: + if sentry_sdk.get_client().get_integration(GnuBacktraceIntegration) is None: return event exc_info = hint.get("exc_info", None) diff --git a/sentry_sdk/integrations/wsgi.py b/sentry_sdk/integrations/wsgi.py index f946844de5..117582ea2f 100644 --- a/sentry_sdk/integrations/wsgi.py +++ b/sentry_sdk/integrations/wsgi.py @@ -6,7 +6,7 @@ from sentry_sdk._werkzeug import get_host, _get_headers from sentry_sdk.api import continue_trace from sentry_sdk.consts import OP -from sentry_sdk.hub import _should_send_default_pii +from sentry_sdk.scope import should_send_default_pii from sentry_sdk.integrations._wsgi_common import _filter_headers from sentry_sdk.sessions import ( auto_session_tracking_scope as auto_session_tracking, @@ -143,7 +143,7 @@ def _get_environ(environ): capture (server name, port and remote addr if pii is enabled). """ keys = ["SERVER_NAME", "SERVER_PORT"] - if _should_send_default_pii(): + if should_send_default_pii(): # make debugging of proxy setup easier. Proxy headers are # in headers. keys += ["REMOTE_ADDR"] @@ -266,7 +266,7 @@ def event_processor(event, hint): # if the code below fails halfway through we at least have some data request_info = event.setdefault("request", {}) - if _should_send_default_pii(): + if should_send_default_pii(): user_info = event.setdefault("user", {}) if client_ip: user_info.setdefault("ip_address", client_ip) diff --git a/sentry_sdk/metrics.py b/sentry_sdk/metrics.py index f750e834a2..dfc1d89734 100644 --- a/sentry_sdk/metrics.py +++ b/sentry_sdk/metrics.py @@ -720,20 +720,18 @@ def _tags_to_dict(tags): def _get_aggregator(): # type: () -> Optional[MetricsAggregator] - hub = sentry_sdk.Hub.current - client = hub.client + client = sentry_sdk.get_client() return ( client.metrics_aggregator - if client is not None and client.metrics_aggregator is not None + if client.is_active() and client.metrics_aggregator is not None else None ) def _get_aggregator_and_update_tags(key, value, unit, tags): # type: (str, Optional[MetricValue], MeasurementUnit, Optional[MetricTags]) -> Tuple[Optional[MetricsAggregator], Optional[LocalAggregator], Optional[MetricTags]] - hub = sentry_sdk.Hub.current - client = hub.client - if client is None or client.metrics_aggregator is None: + client = sentry_sdk.get_client() + if not client.is_active() or client.metrics_aggregator is None: return None, None, tags updated_tags = dict(tags or ()) # type: Dict[str, MetricTagValue] diff --git a/tests/integrations/celery/test_celery.py b/tests/integrations/celery/test_celery.py index 1f3de09620..117d52c81f 100644 --- a/tests/integrations/celery/test_celery.py +++ b/tests/integrations/celery/test_celery.py @@ -6,7 +6,7 @@ from celery import Celery, VERSION from celery.bin import worker -from sentry_sdk import Hub, configure_scope, start_transaction, get_current_span +from sentry_sdk import configure_scope, start_transaction, get_current_span from sentry_sdk.integrations.celery import ( CeleryIntegration, _wrap_apply_async, @@ -60,9 +60,6 @@ def inner( celery.conf.result_backend = "redis://127.0.0.1:6379" celery.conf.task_always_eager = False - Hub.main.bind_client(Hub.current.client) - request.addfinalizer(lambda: Hub.main.bind_client(None)) - # Once we drop celery 3 we can use the celery_worker fixture if VERSION < (5,): worker_fn = worker.worker(app=celery).run @@ -302,45 +299,6 @@ def dummy_task(x, y): assert not events -@pytest.mark.skip( - reason="This tests for a broken rerun in Celery 3. We don't support Celery 3 anymore." -) -def test_broken_prerun(init_celery, connect_signal): - from celery.signals import task_prerun - - stack_lengths = [] - - def crash(*args, **kwargs): - # scope should exist in prerun - stack_lengths.append(len(Hub.current._stack)) - 1 / 0 - - # Order here is important to reproduce the bug: In Celery 3, a crashing - # prerun would prevent other preruns from running. - - connect_signal(task_prerun, crash) - celery = init_celery() - - assert len(Hub.current._stack) == 1 - - @celery.task(name="dummy_task") - def dummy_task(x, y): - stack_lengths.append(len(Hub.current._stack)) - return x / y - - if VERSION >= (4,): - dummy_task.delay(2, 2) - else: - with pytest.raises(ZeroDivisionError): - dummy_task.delay(2, 2) - - assert len(Hub.current._stack) == 1 - if VERSION < (4,): - assert stack_lengths == [2] - else: - assert stack_lengths == [2, 2] - - @pytest.mark.xfail( (4, 2, 0) <= VERSION < (4, 4, 3), strict=True, diff --git a/tests/integrations/conftest.py b/tests/integrations/conftest.py index 9f30ccf076..560155e2b5 100644 --- a/tests/integrations/conftest.py +++ b/tests/integrations/conftest.py @@ -10,6 +10,9 @@ def inner(): old_capture_event_scope = sentry_sdk.Scope.capture_event def capture_event_hub(self, event, hint=None, scope=None): + """ + Can be removed when we remove push_scope and the Hub from the SDK. + """ if hint: if "exc_info" in hint: error = hint["exc_info"][1] diff --git a/tests/test_basics.py b/tests/test_basics.py index 8727e27f35..5407049417 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -8,6 +8,7 @@ from tests.conftest import patch_start_tracing_child +import sentry_sdk from sentry_sdk import ( push_scope, configure_scope, @@ -220,7 +221,7 @@ def before_breadcrumb(crumb, hint): events = capture_events() monkeypatch.setattr( - Hub.current.client.transport, "record_lost_event", record_lost_event + sentry_sdk.get_client().transport, "record_lost_event", record_lost_event ) def do_this(): @@ -269,7 +270,7 @@ def test_option_enable_tracing( updated_traces_sample_rate, ): sentry_init(enable_tracing=enable_tracing, traces_sample_rate=traces_sample_rate) - options = Hub.current.client.options + options = sentry_sdk.get_client().options assert has_tracing_enabled(options) is tracing_enabled assert options["traces_sample_rate"] == updated_traces_sample_rate @@ -311,6 +312,9 @@ def test_push_scope(sentry_init, capture_events): def test_push_scope_null_client(sentry_init, capture_events): + """ + This test can be removed when we remove push_scope and the Hub from the SDK. + """ sentry_init() events = capture_events() @@ -331,6 +335,9 @@ def test_push_scope_null_client(sentry_init, capture_events): ) @pytest.mark.parametrize("null_client", (True, False)) def test_push_scope_callback(sentry_init, null_client, capture_events): + """ + This test can be removed when we remove push_scope and the Hub from the SDK. + """ sentry_init() if null_client: @@ -439,6 +446,9 @@ def test_integration_scoping(sentry_init, capture_events): reason="This test is not valid anymore, because with the new Scopes calling bind_client on the Hub sets the client on the global scope. This test should be removed once the Hub is removed" ) def test_client_initialized_within_scope(sentry_init, caplog): + """ + This test can be removed when we remove push_scope and the Hub from the SDK. + """ caplog.set_level(logging.WARNING) sentry_init() @@ -455,6 +465,9 @@ def test_client_initialized_within_scope(sentry_init, caplog): reason="This test is not valid anymore, because with the new Scopes the push_scope just returns the isolation scope. This test should be removed once the Hub is removed" ) def test_scope_leaks_cleaned_up(sentry_init, caplog): + """ + This test can be removed when we remove push_scope and the Hub from the SDK. + """ caplog.set_level(logging.WARNING) sentry_init() @@ -475,6 +488,9 @@ def test_scope_leaks_cleaned_up(sentry_init, caplog): reason="This test is not valid anymore, because with the new Scopes there is not pushing and popping of scopes. This test should be removed once the Hub is removed" ) def test_scope_popped_too_soon(sentry_init, caplog): + """ + This test can be removed when we remove push_scope and the Hub from the SDK. + """ caplog.set_level(logging.ERROR) sentry_init() @@ -719,7 +735,7 @@ def test_functions_to_trace_with_class(sentry_init, capture_events): def test_redis_disabled_when_not_installed(sentry_init): sentry_init() - assert Hub.current.get_integration(RedisIntegration) is None + assert sentry_sdk.get_client().get_integration(RedisIntegration) is None def test_multiple_setup_integrations_calls(): diff --git a/tests/test_client.py b/tests/test_client.py index 0464f32b5e..a2fea56202 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -9,6 +9,7 @@ import pytest +import sentry_sdk from sentry_sdk import ( Hub, Client, @@ -563,7 +564,11 @@ def capture_envelope(self, envelope): def test_configure_scope_available(sentry_init, request, monkeypatch): - # Test that scope is configured if client is configured + """ + Test that scope is configured if client is configured + + This test can be removed once configure_scope and the Hub are removed. + """ sentry_init() with configure_scope() as scope: @@ -585,7 +590,9 @@ def callback(scope): def test_client_debug_option_enabled(sentry_init, caplog): sentry_init(debug=True) - Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None)) + sentry_sdk.Scope.get_isolation_scope()._capture_internal_exception( + (ValueError, ValueError("OK"), None) + ) assert "OK" in caplog.text @@ -595,7 +602,9 @@ def test_client_debug_option_disabled(with_client, sentry_init, caplog): if with_client: sentry_init() - Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None)) + sentry_sdk.Scope.get_isolation_scope()._capture_internal_exception( + (ValueError, ValueError("OK"), None) + ) assert "OK" not in caplog.text @@ -949,7 +958,7 @@ def test_init_string_types(dsn, sentry_init): # extra code sentry_init(dsn) assert ( - Hub.current.client.dsn + sentry_sdk.get_client().dsn == "http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2" ) @@ -1047,7 +1056,7 @@ def test_debug_option( else: sentry_init(debug=client_option) - Hub.current._capture_internal_exception( + sentry_sdk.Scope.get_isolation_scope()._capture_internal_exception( (ValueError, ValueError("something is wrong"), None) ) if debug_output_expected: diff --git a/tests/test_crons.py b/tests/test_crons.py index 2b4ed3cab2..493cc44272 100644 --- a/tests/test_crons.py +++ b/tests/test_crons.py @@ -4,7 +4,7 @@ import pytest import sentry_sdk -from sentry_sdk import Hub, configure_scope, set_level + from sentry_sdk.crons import capture_checkin @@ -322,6 +322,8 @@ def test_scope_data_in_checkin(sentry_init, capture_envelopes): # Optional event keys "release", "environment", + "server_name", + "sdk", # Mandatory check-in specific keys "check_in_id", "monitor_slug", @@ -330,42 +332,33 @@ def test_scope_data_in_checkin(sentry_init, capture_envelopes): "duration", "monitor_config", "contexts", # an event processor adds this - # TODO: These fields need to be checked if valid for checkin: - "_meta", - "tags", - "extra", # an event processor adds this - "modules", - "server_name", - "sdk", ] - hub = Hub.current - with configure_scope() as scope: - # Add some data to the scope - set_level("warning") - hub.add_breadcrumb(message="test breadcrumb") - scope.set_tag("test_tag", "test_value") - scope.set_extra("test_extra", "test_value") - scope.set_context("test_context", {"test_key": "test_value"}) + # Add some data to the scope + sentry_sdk.add_breadcrumb(message="test breadcrumb") + sentry_sdk.set_context("test_context", {"test_key": "test_value"}) + sentry_sdk.set_extra("test_extra", "test_value") + sentry_sdk.set_level("warning") + sentry_sdk.set_tag("test_tag", "test_value") - capture_checkin( - monitor_slug="abc123", - check_in_id="112233", - status="ok", - duration=123, - ) + capture_checkin( + monitor_slug="abc123", + check_in_id="112233", + status="ok", + duration=123, + ) - (envelope,) = envelopes - check_in_event = envelope.items[0].payload.json + (envelope,) = envelopes + check_in_event = envelope.items[0].payload.json - invalid_keys = [] - for key in check_in_event.keys(): - if key not in valid_keys: - invalid_keys.append(key) + invalid_keys = [] + for key in check_in_event.keys(): + if key not in valid_keys: + invalid_keys.append(key) - assert len(invalid_keys) == 0, "Unexpected keys found in checkin: {}".format( - invalid_keys - ) + assert len(invalid_keys) == 0, "Unexpected keys found in checkin: {}".format( + invalid_keys + ) @pytest.mark.asyncio diff --git a/tests/test_metrics.py b/tests/test_metrics.py index c0793e8015..a29a18b0cf 100644 --- a/tests/test_metrics.py +++ b/tests/test_metrics.py @@ -5,7 +5,8 @@ import pytest -from sentry_sdk import Hub, Scope, metrics, start_transaction +import sentry_sdk +from sentry_sdk import Scope, metrics from sentry_sdk.tracing import TRANSACTION_SOURCE_ROUTE from sentry_sdk.envelope import parse_json @@ -66,7 +67,7 @@ def test_increment(sentry_init, capture_envelopes, maybe_monkeypatched_threading metrics.increment("foobar", 1.0, tags={"foo": "bar", "blub": "blah"}, timestamp=ts) # python specific alias metrics.incr("foobar", 2.0, tags={"foo": "bar", "blub": "blah"}, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes statsd_item, meta_item = envelope.items @@ -119,7 +120,7 @@ def test_timing(sentry_init, capture_envelopes, maybe_monkeypatched_threading): with metrics.timing("whatever", tags={"blub": "blah"}, timestamp=ts): time.sleep(0.1) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes statsd_item, meta_item = envelope.items @@ -191,7 +192,7 @@ def amazing_nano(): assert amazing() == 42 assert amazing_nano() == 23 - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes statsd_item, meta_item = envelope.items @@ -278,7 +279,7 @@ def test_timing_basic(sentry_init, capture_envelopes, maybe_monkeypatched_thread metrics.timing("timing", 2.0, tags={"a": "b"}, timestamp=ts) metrics.timing("timing", 2.0, tags={"a": "b"}, timestamp=ts) metrics.timing("timing", 3.0, tags={"a": "b"}, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes statsd_item, meta_item = envelope.items @@ -333,7 +334,7 @@ def test_distribution(sentry_init, capture_envelopes, maybe_monkeypatched_thread metrics.distribution("dist", 2.0, tags={"a": "b"}, timestamp=ts) metrics.distribution("dist", 2.0, tags={"a": "b"}, timestamp=ts) metrics.distribution("dist", 3.0, tags={"a": "b"}, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes statsd_item, meta_item = envelope.items @@ -395,7 +396,7 @@ def test_set(sentry_init, capture_envelopes, maybe_monkeypatched_threading): metrics.set("my-set", "peter", tags={"magic": "puff"}, timestamp=ts) metrics.set("my-set", "paul", tags={"magic": "puff"}, timestamp=ts) metrics.set("my-set", "mary", tags={"magic": "puff"}, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes statsd_item, meta_item = envelope.items @@ -449,7 +450,7 @@ def test_gauge(sentry_init, capture_envelopes, maybe_monkeypatched_threading): metrics.gauge("my-gauge", 10.0, tags={"x": "y"}, timestamp=ts) metrics.gauge("my-gauge", 20.0, tags={"x": "y"}, timestamp=ts) metrics.gauge("my-gauge", 30.0, tags={"x": "y"}, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -487,7 +488,7 @@ def test_multiple(sentry_init, capture_envelopes): metrics.increment("counter-1", 1.0, timestamp=ts) metrics.increment("counter-2", 1.0, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -544,7 +545,7 @@ def test_transaction_name( metrics.distribution("dist", 2.0, tags={"a": "b"}, timestamp=ts) metrics.distribution("dist", 3.0, tags={"a": "b"}, timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -578,7 +579,7 @@ def test_metric_summaries( ts = time.time() envelopes = capture_envelopes() - with start_transaction( + with sentry_sdk.start_transaction( op="stuff", name="/foo", source=TRANSACTION_SOURCE_ROUTE ) as transaction: metrics.increment("root-counter", timestamp=ts) @@ -586,7 +587,7 @@ def test_metric_summaries( for x in range(10): metrics.distribution("my-dist", float(x), timestamp=ts) - Hub.current.flush() + sentry_sdk.flush() (transaction, envelope) = envelopes @@ -706,7 +707,7 @@ def test_metric_name_normalization( metrics.distribution(metric_name, 1.0, unit=metric_unit) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -750,7 +751,7 @@ def test_metric_tag_normalization( metrics.distribution("a", 1.0, tags=metric_tag) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -797,7 +798,7 @@ def before_emit(key, value, unit, tags): metrics.increment("another-removed-metric", 47) metrics.increment("yet-another-removed-metric", 1.0, unit="unsupported") metrics.increment("actual-metric", 1.0) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -829,10 +830,10 @@ def test_aggregator_flush( envelopes = capture_envelopes() metrics.increment("a-metric", 1.0) - Hub.current.flush() + sentry_sdk.flush() assert len(envelopes) == 1 - assert Hub.current.client.metrics_aggregator.buckets == {} + assert sentry_sdk.get_client().metrics_aggregator.buckets == {} @minimum_python_37_with_gevent @@ -857,7 +858,7 @@ def test_tag_serialization( "more-than-one": [1, "zwei", "3.0", None], }, ) - Hub.current.flush() + sentry_sdk.flush() (envelope,) = envelopes @@ -887,7 +888,7 @@ def test_flush_recursion_protection( _experiments={"enable_metrics": True}, ) envelopes = capture_envelopes() - test_client = Hub.current.client + test_client = sentry_sdk.get_client() real_capture_envelope = test_client.transport.capture_envelope @@ -900,8 +901,8 @@ def bad_capture_envelope(*args, **kwargs): metrics.increment("counter") # flush twice to see the inner metric - Hub.current.flush() - Hub.current.flush() + sentry_sdk.flush() + sentry_sdk.flush() (envelope,) = envelopes m = parse_metrics(envelope.items[0].payload.get_bytes()) @@ -921,7 +922,7 @@ def test_flush_recursion_protection_background_flush( _experiments={"enable_metrics": True}, ) envelopes = capture_envelopes() - test_client = Hub.current.client + test_client = sentry_sdk.get_client() real_capture_envelope = test_client.transport.capture_envelope @@ -934,7 +935,7 @@ def bad_capture_envelope(*args, **kwargs): metrics.increment("counter") # flush via sleep and flag - Hub.current.client.metrics_aggregator._force_flush = True + sentry_sdk.get_client().metrics_aggregator._force_flush = True time.sleep(0.5) (envelope,) = envelopes @@ -963,7 +964,7 @@ def test_disable_metrics_for_old_python_with_gevent( metrics.incr("counter") - Hub.current.flush() + sentry_sdk.flush() - assert Hub.current.client.metrics_aggregator is None + assert sentry_sdk.get_client().metrics_aggregator is None assert not envelopes diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 3822437df3..61b71f06bd 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -1,7 +1,7 @@ import random from unittest import mock -from sentry_sdk import Hub, start_transaction +import sentry_sdk from sentry_sdk.transport import Transport @@ -24,13 +24,13 @@ def test_no_monitor_if_disabled(sentry_init): enable_backpressure_handling=False, ) - assert Hub.current.client.monitor is None + assert sentry_sdk.get_client().monitor is None def test_monitor_if_enabled(sentry_init): sentry_init(transport=HealthyTestTransport()) - monitor = Hub.current.client.monitor + monitor = sentry_sdk.get_client().monitor assert monitor is not None assert monitor._thread is None @@ -43,7 +43,7 @@ def test_monitor_if_enabled(sentry_init): def test_monitor_unhealthy(sentry_init): sentry_init(transport=UnhealthyTestTransport()) - monitor = Hub.current.client.monitor + monitor = sentry_sdk.get_client().monitor monitor.interval = 0.1 assert monitor.is_healthy() is True @@ -64,7 +64,7 @@ def test_transaction_uses_downsampled_rate( reports = capture_client_reports() - monitor = Hub.current.client.monitor + monitor = sentry_sdk.get_client().monitor monitor.interval = 0.1 # make sure rng doesn't sample @@ -75,7 +75,7 @@ def test_transaction_uses_downsampled_rate( assert monitor.is_healthy() is False assert monitor.downsample_factor == 1 - with start_transaction(name="foobar") as transaction: + with sentry_sdk.start_transaction(name="foobar") as transaction: assert transaction.sampled is False assert transaction.sample_rate == 0.5 @@ -90,7 +90,7 @@ def test_monitor_no_thread_on_shutdown_no_errors(sentry_init): "threading.Thread.start", side_effect=RuntimeError("can't create new thread at interpreter shutdown"), ): - monitor = Hub.current.client.monitor + monitor = sentry_sdk.get_client().monitor assert monitor is not None assert monitor._thread is None monitor.run() diff --git a/tests/test_sessions.py b/tests/test_sessions.py index 91ce9cc58b..989bfeadd1 100644 --- a/tests/test_sessions.py +++ b/tests/test_sessions.py @@ -1,7 +1,6 @@ from unittest import mock import sentry_sdk -from sentry_sdk import Hub from sentry_sdk.sessions import auto_session_tracking @@ -15,17 +14,17 @@ def test_basic(sentry_init, capture_envelopes): sentry_init(release="fun-release", environment="not-fun-env") envelopes = capture_envelopes() - hub = Hub.current - hub.start_session() + sentry_sdk.Scope.get_isolation_scope().start_session() try: - with hub.configure_scope() as scope: - scope.set_user({"id": "42"}) - raise Exception("all is wrong") + scope = sentry_sdk.Scope.get_current_scope() + scope.set_user({"id": "42"}) + raise Exception("all is wrong") except Exception: - hub.capture_exception() - hub.end_session() - hub.flush() + sentry_sdk.capture_exception() + + sentry_sdk.Scope.get_isolation_scope().end_session() + sentry_sdk.flush() assert len(envelopes) == 2 assert envelopes[0].get_event() is not None @@ -51,23 +50,20 @@ def test_aggregates(sentry_init, capture_envelopes): ) envelopes = capture_envelopes() - hub = Hub.current - with auto_session_tracking(session_mode="request"): with sentry_sdk.push_scope(): try: - with sentry_sdk.configure_scope() as scope: - scope.set_user({"id": "42"}) - raise Exception("all is wrong") + scope = sentry_sdk.Scope.get_current_scope() + scope.set_user({"id": "42"}) + raise Exception("all is wrong") except Exception: sentry_sdk.capture_exception() with auto_session_tracking(session_mode="request"): pass - hub.start_session(session_mode="request") - hub.end_session() - + sentry_sdk.Scope.get_isolation_scope().start_session(session_mode="request") + sentry_sdk.Scope.get_isolation_scope().end_session() sentry_sdk.flush() assert len(envelopes) == 2 @@ -95,8 +91,6 @@ def test_aggregates_explicitly_disabled_session_tracking_request_mode( ) envelopes = capture_envelopes() - hub = Hub.current - with auto_session_tracking(session_mode="request"): with sentry_sdk.push_scope(): try: @@ -107,9 +101,8 @@ def test_aggregates_explicitly_disabled_session_tracking_request_mode( with auto_session_tracking(session_mode="request"): pass - hub.start_session(session_mode="request") - hub.end_session() - + sentry_sdk.Scope.get_isolation_scope().start_session(session_mode="request") + sentry_sdk.Scope.get_isolation_scope().end_session() sentry_sdk.flush() sess = envelopes[1] @@ -128,8 +121,6 @@ def test_no_thread_on_shutdown_no_errors(sentry_init): environment="not-fun-env", ) - hub = Hub.current - # make it seem like the interpreter is shutting down with mock.patch( "threading.Thread.start", @@ -145,7 +136,6 @@ def test_no_thread_on_shutdown_no_errors(sentry_init): with auto_session_tracking(session_mode="request"): pass - hub.start_session(session_mode="request") - hub.end_session() - + sentry_sdk.Scope.get_isolation_scope().start_session(session_mode="request") + sentry_sdk.Scope.get_isolation_scope().end_session() sentry_sdk.flush() diff --git a/tests/test_spotlight.py b/tests/test_spotlight.py index f0ab4664e0..d00c4eb8fc 100644 --- a/tests/test_spotlight.py +++ b/tests/test_spotlight.py @@ -1,13 +1,13 @@ import pytest -from sentry_sdk import Hub, capture_exception +import sentry_sdk @pytest.fixture def capture_spotlight_envelopes(monkeypatch): def inner(): envelopes = [] - test_spotlight = Hub.current.client.spotlight + test_spotlight = sentry_sdk.get_client().spotlight old_capture_envelope = test_spotlight.capture_envelope def append_envelope(envelope): @@ -22,13 +22,13 @@ def append_envelope(envelope): def test_spotlight_off_by_default(sentry_init): sentry_init() - assert Hub.current.client.spotlight is None + assert sentry_sdk.get_client().spotlight is None def test_spotlight_default_url(sentry_init): sentry_init(spotlight=True) - spotlight = Hub.current.client.spotlight + spotlight = sentry_sdk.get_client().spotlight assert spotlight is not None assert spotlight.url == "http://localhost:8969/stream" @@ -36,7 +36,7 @@ def test_spotlight_default_url(sentry_init): def test_spotlight_custom_url(sentry_init): sentry_init(spotlight="http://foobar@test.com/132") - spotlight = Hub.current.client.spotlight + spotlight = sentry_sdk.get_client().spotlight assert spotlight is not None assert spotlight.url == "http://foobar@test.com/132" @@ -48,7 +48,7 @@ def test_spotlight_envelope(sentry_init, capture_spotlight_envelopes): try: raise ValueError("aha!") except Exception: - capture_exception() + sentry_sdk.capture_exception() (envelope,) = envelopes payload = envelope.items[0].payload.json diff --git a/tests/test_transport.py b/tests/test_transport.py index 73eee6d353..6cace6f418 100644 --- a/tests/test_transport.py +++ b/tests/test_transport.py @@ -11,7 +11,8 @@ from pytest_localserver.http import WSGIServer from werkzeug.wrappers import Request, Response -from sentry_sdk import Hub, Client, add_breadcrumb, capture_message, Scope +import sentry_sdk +from sentry_sdk import Client, add_breadcrumb, capture_message, Scope from sentry_sdk.envelope import Envelope, Item, parse_json from sentry_sdk.transport import KEEP_ALIVE_SOCKET_OPTIONS, _parse_rate_limits from sentry_sdk.integrations.logging import LoggingIntegration, ignore_logger @@ -114,8 +115,8 @@ def test_transport_works( if use_pickle: client = pickle.loads(pickle.dumps(client)) - Hub.current.bind_client(client) - request.addfinalizer(lambda: Hub.current.bind_client(None)) + sentry_sdk.Scope.get_global_scope().set_client(client) + request.addfinalizer(lambda: sentry_sdk.Scope.get_global_scope().set_client(None)) add_breadcrumb( level="info", message="i like bread", timestamp=datetime.now(timezone.utc) @@ -238,7 +239,8 @@ def test_transport_infinite_loop(capturing_server, request, make_client): # to an infinite loop ignore_logger("werkzeug") - with Hub(client): + sentry_sdk.Scope.get_global_scope().set_client(client) + with sentry_sdk.isolation_scope(): capture_message("hi") client.flush() @@ -253,7 +255,8 @@ def test_transport_no_thread_on_shutdown_no_errors(capturing_server, make_client "threading.Thread.start", side_effect=RuntimeError("can't create new thread at interpreter shutdown"), ): - with Hub(client): + sentry_sdk.Scope.get_global_scope().set_client(client) + with sentry_sdk.isolation_scope(): capture_message("hi") # nothing exploded but also no events can be sent anymore diff --git a/tests/test_utils.py b/tests/test_utils.py index dd3aa3817a..c4064729f8 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -453,7 +453,7 @@ def test_parse_version(version, expected_result): @pytest.fixture def mock_client_with_dsn_netloc(): """ - Returns a mocked hub with a DSN netloc of "abcd1234.ingest.sentry.io". + Returns a mocked Client with a DSN netloc of "abcd1234.ingest.sentry.io". """ mock_client = mock.Mock(spec=sentry_sdk.Client) mock_client.transport = mock.Mock(spec=sentry_sdk.Transport) @@ -808,7 +808,7 @@ def test_get_current_thread_meta_gevent_in_thread_failed_to_get_hub(): def target(): with mock.patch("sentry_sdk.utils.is_gevent", side_effect=[True]): with mock.patch( - "sentry_sdk.utils.get_gevent_hub", side_effect=["fake hub"] + "sentry_sdk.utils.get_gevent_hub", side_effect=["fake gevent hub"] ): job = gevent.spawn(get_current_thread_meta) job.join() diff --git a/tests/tracing/test_integration_tests.py b/tests/tracing/test_integration_tests.py index 9543014cac..4752c9a131 100644 --- a/tests/tracing/test_integration_tests.py +++ b/tests/tracing/test_integration_tests.py @@ -6,7 +6,6 @@ from sentry_sdk import ( capture_message, - Hub, Scope, start_span, start_transaction, @@ -65,7 +64,9 @@ def test_continue_from_headers(sentry_init, capture_envelopes, sampled, sample_r with start_transaction(name="hi", sampled=True if sample_rate == 0 else None): with start_span() as old_span: old_span.sampled = sampled - headers = dict(Hub.current.iter_trace_propagation_headers(old_span)) + headers = dict( + Scope.get_current_scope().iter_trace_propagation_headers(old_span) + ) headers["baggage"] = ( "other-vendor-value-1=foo;bar;baz, " "sentry-trace_id=771a43a4192642f0b136d5159a501700, " @@ -269,7 +270,7 @@ def test_trace_propagation_meta_head_sdk(sentry_init): with start_transaction(transaction): with start_span(op="foo", description="foodesc") as current_span: span = current_span - meta = Hub.current.trace_propagation_meta() + meta = Scope.get_current_scope().trace_propagation_meta() ind = meta.find(">") + 1 sentry_trace, baggage = meta[:ind], meta[ind:] diff --git a/tests/tracing/test_misc.py b/tests/tracing/test_misc.py index e1006ef1bb..6d722e992f 100644 --- a/tests/tracing/test_misc.py +++ b/tests/tracing/test_misc.py @@ -6,7 +6,7 @@ from unittest.mock import MagicMock import sentry_sdk -from sentry_sdk import Hub, Scope, start_span, start_transaction, set_measurement +from sentry_sdk import Scope, start_span, start_transaction, set_measurement from sentry_sdk.consts import MATCH_ALL from sentry_sdk.tracing import Span, Transaction from sentry_sdk.tracing_utils import should_propagate_trace @@ -84,7 +84,7 @@ def test_finds_transaction_on_scope(sentry_init): transaction = start_transaction(name="dogpark") - scope = Hub.current.scope + scope = Scope.get_current_scope() # See note in Scope class re: getters and setters of the `transaction` # property. For the moment, assigning to scope.transaction merely sets the @@ -113,7 +113,7 @@ def test_finds_transaction_when_descendent_span_is_on_scope( transaction = start_transaction(name="dogpark") child_span = transaction.start_child(op="sniffing") - scope = Hub.current.scope + scope = Scope.get_current_scope() scope._span = child_span # this is the same whether it's the transaction itself or one of its @@ -136,7 +136,7 @@ def test_finds_orphan_span_on_scope(sentry_init): span = start_span(op="sniffing") - scope = Hub.current.scope + scope = Scope.get_current_scope() scope._span = span assert scope._span is not None @@ -150,7 +150,7 @@ def test_finds_non_orphan_span_on_scope(sentry_init): transaction = start_transaction(name="dogpark") child_span = transaction.start_child(op="sniffing") - scope = Hub.current.scope + scope = Scope.get_current_scope() scope._span = child_span assert scope._span is not None diff --git a/tests/tracing/test_sampling.py b/tests/tracing/test_sampling.py index 1940656bdf..88fb048d57 100644 --- a/tests/tracing/test_sampling.py +++ b/tests/tracing/test_sampling.py @@ -3,7 +3,8 @@ import pytest -from sentry_sdk import Hub, Scope, start_span, start_transaction, capture_exception +import sentry_sdk +from sentry_sdk import Scope, start_span, start_transaction, capture_exception from sentry_sdk.tracing import Transaction from sentry_sdk.utils import logger @@ -278,7 +279,7 @@ def record_lost_event(reason, data_category=None, item=None): sentry_init(traces_sample_rate=traces_sample_rate) monkeypatch.setattr( - Hub.current.client.transport, "record_lost_event", record_lost_event + sentry_sdk.get_client().transport, "record_lost_event", record_lost_event ) transaction = start_transaction(name="dogpark") @@ -307,7 +308,7 @@ def record_lost_event(reason, data_category=None, item=None): sentry_init(traces_sampler=traces_sampler) monkeypatch.setattr( - Hub.current.client.transport, "record_lost_event", record_lost_event + sentry_sdk.get_client().transport, "record_lost_event", record_lost_event ) transaction = start_transaction(name="dogpark")