Skip to content

Commit ac5c8e8

Browse files
authored
Remove Hub from our test suite (#3197)
Remove Hub usage from our test suite. We keep the tests that test the hubs/scopes-refactoring until we actually remove the Hub from the public API. Also removing Hub usage from some of our integrations.
1 parent 6c7374e commit ac5c8e8

18 files changed

+151
-178
lines changed

sentry_sdk/integrations/_asgi_common.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import urllib
22

3-
from sentry_sdk.hub import _should_send_default_pii
3+
from sentry_sdk.scope import should_send_default_pii
44
from sentry_sdk.integrations._wsgi_common import _filter_headers
55
from sentry_sdk._types import TYPE_CHECKING
66

@@ -101,7 +101,7 @@ def _get_request_data(asgi_scope):
101101
)
102102

103103
client = asgi_scope.get("client")
104-
if client and _should_send_default_pii():
104+
if client and should_send_default_pii():
105105
request_data["env"] = {"REMOTE_ADDR": _get_ip(asgi_scope)}
106106

107107
return request_data

sentry_sdk/integrations/gnu_backtrace.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import re
22

3-
from sentry_sdk.hub import Hub
3+
import sentry_sdk
44
from sentry_sdk.integrations import Integration
55
from sentry_sdk.scope import add_global_event_processor
66
from sentry_sdk.utils import capture_internal_exceptions
@@ -49,7 +49,7 @@ def process_gnu_backtrace(event, hint):
4949

5050
def _process_gnu_backtrace(event, hint):
5151
# type: (Event, dict[str, Any]) -> Event
52-
if Hub.current.get_integration(GnuBacktraceIntegration) is None:
52+
if sentry_sdk.get_client().get_integration(GnuBacktraceIntegration) is None:
5353
return event
5454

5555
exc_info = hint.get("exc_info", None)

sentry_sdk/integrations/wsgi.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from sentry_sdk._werkzeug import get_host, _get_headers
77
from sentry_sdk.api import continue_trace
88
from sentry_sdk.consts import OP
9-
from sentry_sdk.hub import _should_send_default_pii
9+
from sentry_sdk.scope import should_send_default_pii
1010
from sentry_sdk.integrations._wsgi_common import _filter_headers
1111
from sentry_sdk.sessions import (
1212
auto_session_tracking_scope as auto_session_tracking,
@@ -143,7 +143,7 @@ def _get_environ(environ):
143143
capture (server name, port and remote addr if pii is enabled).
144144
"""
145145
keys = ["SERVER_NAME", "SERVER_PORT"]
146-
if _should_send_default_pii():
146+
if should_send_default_pii():
147147
# make debugging of proxy setup easier. Proxy headers are
148148
# in headers.
149149
keys += ["REMOTE_ADDR"]
@@ -266,7 +266,7 @@ def event_processor(event, hint):
266266
# if the code below fails halfway through we at least have some data
267267
request_info = event.setdefault("request", {})
268268

269-
if _should_send_default_pii():
269+
if should_send_default_pii():
270270
user_info = event.setdefault("user", {})
271271
if client_ip:
272272
user_info.setdefault("ip_address", client_ip)

sentry_sdk/metrics.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -720,20 +720,18 @@ def _tags_to_dict(tags):
720720

721721
def _get_aggregator():
722722
# type: () -> Optional[MetricsAggregator]
723-
hub = sentry_sdk.Hub.current
724-
client = hub.client
723+
client = sentry_sdk.get_client()
725724
return (
726725
client.metrics_aggregator
727-
if client is not None and client.metrics_aggregator is not None
726+
if client.is_active() and client.metrics_aggregator is not None
728727
else None
729728
)
730729

731730

732731
def _get_aggregator_and_update_tags(key, value, unit, tags):
733732
# type: (str, Optional[MetricValue], MeasurementUnit, Optional[MetricTags]) -> Tuple[Optional[MetricsAggregator], Optional[LocalAggregator], Optional[MetricTags]]
734-
hub = sentry_sdk.Hub.current
735-
client = hub.client
736-
if client is None or client.metrics_aggregator is None:
733+
client = sentry_sdk.get_client()
734+
if not client.is_active() or client.metrics_aggregator is None:
737735
return None, None, tags
738736

739737
updated_tags = dict(tags or ()) # type: Dict[str, MetricTagValue]

tests/integrations/celery/test_celery.py

Lines changed: 1 addition & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from celery import Celery, VERSION
77
from celery.bin import worker
88

9-
from sentry_sdk import Hub, configure_scope, start_transaction, get_current_span
9+
from sentry_sdk import configure_scope, start_transaction, get_current_span
1010
from sentry_sdk.integrations.celery import (
1111
CeleryIntegration,
1212
_wrap_apply_async,
@@ -60,9 +60,6 @@ def inner(
6060
celery.conf.result_backend = "redis://127.0.0.1:6379"
6161
celery.conf.task_always_eager = False
6262

63-
Hub.main.bind_client(Hub.current.client)
64-
request.addfinalizer(lambda: Hub.main.bind_client(None))
65-
6663
# Once we drop celery 3 we can use the celery_worker fixture
6764
if VERSION < (5,):
6865
worker_fn = worker.worker(app=celery).run
@@ -302,45 +299,6 @@ def dummy_task(x, y):
302299
assert not events
303300

304301

305-
@pytest.mark.skip(
306-
reason="This tests for a broken rerun in Celery 3. We don't support Celery 3 anymore."
307-
)
308-
def test_broken_prerun(init_celery, connect_signal):
309-
from celery.signals import task_prerun
310-
311-
stack_lengths = []
312-
313-
def crash(*args, **kwargs):
314-
# scope should exist in prerun
315-
stack_lengths.append(len(Hub.current._stack))
316-
1 / 0
317-
318-
# Order here is important to reproduce the bug: In Celery 3, a crashing
319-
# prerun would prevent other preruns from running.
320-
321-
connect_signal(task_prerun, crash)
322-
celery = init_celery()
323-
324-
assert len(Hub.current._stack) == 1
325-
326-
@celery.task(name="dummy_task")
327-
def dummy_task(x, y):
328-
stack_lengths.append(len(Hub.current._stack))
329-
return x / y
330-
331-
if VERSION >= (4,):
332-
dummy_task.delay(2, 2)
333-
else:
334-
with pytest.raises(ZeroDivisionError):
335-
dummy_task.delay(2, 2)
336-
337-
assert len(Hub.current._stack) == 1
338-
if VERSION < (4,):
339-
assert stack_lengths == [2]
340-
else:
341-
assert stack_lengths == [2, 2]
342-
343-
344302
@pytest.mark.xfail(
345303
(4, 2, 0) <= VERSION < (4, 4, 3),
346304
strict=True,

tests/integrations/conftest.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ def inner():
1010
old_capture_event_scope = sentry_sdk.Scope.capture_event
1111

1212
def capture_event_hub(self, event, hint=None, scope=None):
13+
"""
14+
Can be removed when we remove push_scope and the Hub from the SDK.
15+
"""
1316
if hint:
1417
if "exc_info" in hint:
1518
error = hint["exc_info"][1]

tests/test_basics.py

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88

99
from tests.conftest import patch_start_tracing_child
1010

11+
import sentry_sdk
1112
from sentry_sdk import (
1213
push_scope,
1314
configure_scope,
@@ -220,7 +221,7 @@ def before_breadcrumb(crumb, hint):
220221
events = capture_events()
221222

222223
monkeypatch.setattr(
223-
Hub.current.client.transport, "record_lost_event", record_lost_event
224+
sentry_sdk.get_client().transport, "record_lost_event", record_lost_event
224225
)
225226

226227
def do_this():
@@ -269,7 +270,7 @@ def test_option_enable_tracing(
269270
updated_traces_sample_rate,
270271
):
271272
sentry_init(enable_tracing=enable_tracing, traces_sample_rate=traces_sample_rate)
272-
options = Hub.current.client.options
273+
options = sentry_sdk.get_client().options
273274
assert has_tracing_enabled(options) is tracing_enabled
274275
assert options["traces_sample_rate"] == updated_traces_sample_rate
275276

@@ -311,6 +312,9 @@ def test_push_scope(sentry_init, capture_events):
311312

312313

313314
def test_push_scope_null_client(sentry_init, capture_events):
315+
"""
316+
This test can be removed when we remove push_scope and the Hub from the SDK.
317+
"""
314318
sentry_init()
315319
events = capture_events()
316320

@@ -331,6 +335,9 @@ def test_push_scope_null_client(sentry_init, capture_events):
331335
)
332336
@pytest.mark.parametrize("null_client", (True, False))
333337
def test_push_scope_callback(sentry_init, null_client, capture_events):
338+
"""
339+
This test can be removed when we remove push_scope and the Hub from the SDK.
340+
"""
334341
sentry_init()
335342

336343
if null_client:
@@ -439,6 +446,9 @@ def test_integration_scoping(sentry_init, capture_events):
439446
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"
440447
)
441448
def test_client_initialized_within_scope(sentry_init, caplog):
449+
"""
450+
This test can be removed when we remove push_scope and the Hub from the SDK.
451+
"""
442452
caplog.set_level(logging.WARNING)
443453

444454
sentry_init()
@@ -455,6 +465,9 @@ def test_client_initialized_within_scope(sentry_init, caplog):
455465
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"
456466
)
457467
def test_scope_leaks_cleaned_up(sentry_init, caplog):
468+
"""
469+
This test can be removed when we remove push_scope and the Hub from the SDK.
470+
"""
458471
caplog.set_level(logging.WARNING)
459472

460473
sentry_init()
@@ -475,6 +488,9 @@ def test_scope_leaks_cleaned_up(sentry_init, caplog):
475488
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"
476489
)
477490
def test_scope_popped_too_soon(sentry_init, caplog):
491+
"""
492+
This test can be removed when we remove push_scope and the Hub from the SDK.
493+
"""
478494
caplog.set_level(logging.ERROR)
479495

480496
sentry_init()
@@ -719,7 +735,7 @@ def test_functions_to_trace_with_class(sentry_init, capture_events):
719735
def test_redis_disabled_when_not_installed(sentry_init):
720736
sentry_init()
721737

722-
assert Hub.current.get_integration(RedisIntegration) is None
738+
assert sentry_sdk.get_client().get_integration(RedisIntegration) is None
723739

724740

725741
def test_multiple_setup_integrations_calls():

tests/test_client.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
import pytest
1111

12+
import sentry_sdk
1213
from sentry_sdk import (
1314
Hub,
1415
Client,
@@ -563,7 +564,11 @@ def capture_envelope(self, envelope):
563564

564565

565566
def test_configure_scope_available(sentry_init, request, monkeypatch):
566-
# Test that scope is configured if client is configured
567+
"""
568+
Test that scope is configured if client is configured
569+
570+
This test can be removed once configure_scope and the Hub are removed.
571+
"""
567572
sentry_init()
568573

569574
with configure_scope() as scope:
@@ -585,7 +590,9 @@ def callback(scope):
585590
def test_client_debug_option_enabled(sentry_init, caplog):
586591
sentry_init(debug=True)
587592

588-
Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None))
593+
sentry_sdk.Scope.get_isolation_scope()._capture_internal_exception(
594+
(ValueError, ValueError("OK"), None)
595+
)
589596
assert "OK" in caplog.text
590597

591598

@@ -595,7 +602,9 @@ def test_client_debug_option_disabled(with_client, sentry_init, caplog):
595602
if with_client:
596603
sentry_init()
597604

598-
Hub.current._capture_internal_exception((ValueError, ValueError("OK"), None))
605+
sentry_sdk.Scope.get_isolation_scope()._capture_internal_exception(
606+
(ValueError, ValueError("OK"), None)
607+
)
599608
assert "OK" not in caplog.text
600609

601610

@@ -949,7 +958,7 @@ def test_init_string_types(dsn, sentry_init):
949958
# extra code
950959
sentry_init(dsn)
951960
assert (
952-
Hub.current.client.dsn
961+
sentry_sdk.get_client().dsn
953962
== "http://894b7d594095440f8dfea9b300e6f572@localhost:8000/2"
954963
)
955964

@@ -1047,7 +1056,7 @@ def test_debug_option(
10471056
else:
10481057
sentry_init(debug=client_option)
10491058

1050-
Hub.current._capture_internal_exception(
1059+
sentry_sdk.Scope.get_isolation_scope()._capture_internal_exception(
10511060
(ValueError, ValueError("something is wrong"), None)
10521061
)
10531062
if debug_output_expected:

tests/test_crons.py

Lines changed: 24 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import pytest
55

66
import sentry_sdk
7-
from sentry_sdk import Hub, configure_scope, set_level
7+
88
from sentry_sdk.crons import capture_checkin
99

1010

@@ -322,6 +322,8 @@ def test_scope_data_in_checkin(sentry_init, capture_envelopes):
322322
# Optional event keys
323323
"release",
324324
"environment",
325+
"server_name",
326+
"sdk",
325327
# Mandatory check-in specific keys
326328
"check_in_id",
327329
"monitor_slug",
@@ -330,42 +332,33 @@ def test_scope_data_in_checkin(sentry_init, capture_envelopes):
330332
"duration",
331333
"monitor_config",
332334
"contexts", # an event processor adds this
333-
# TODO: These fields need to be checked if valid for checkin:
334-
"_meta",
335-
"tags",
336-
"extra", # an event processor adds this
337-
"modules",
338-
"server_name",
339-
"sdk",
340335
]
341336

342-
hub = Hub.current
343-
with configure_scope() as scope:
344-
# Add some data to the scope
345-
set_level("warning")
346-
hub.add_breadcrumb(message="test breadcrumb")
347-
scope.set_tag("test_tag", "test_value")
348-
scope.set_extra("test_extra", "test_value")
349-
scope.set_context("test_context", {"test_key": "test_value"})
337+
# Add some data to the scope
338+
sentry_sdk.add_breadcrumb(message="test breadcrumb")
339+
sentry_sdk.set_context("test_context", {"test_key": "test_value"})
340+
sentry_sdk.set_extra("test_extra", "test_value")
341+
sentry_sdk.set_level("warning")
342+
sentry_sdk.set_tag("test_tag", "test_value")
350343

351-
capture_checkin(
352-
monitor_slug="abc123",
353-
check_in_id="112233",
354-
status="ok",
355-
duration=123,
356-
)
344+
capture_checkin(
345+
monitor_slug="abc123",
346+
check_in_id="112233",
347+
status="ok",
348+
duration=123,
349+
)
357350

358-
(envelope,) = envelopes
359-
check_in_event = envelope.items[0].payload.json
351+
(envelope,) = envelopes
352+
check_in_event = envelope.items[0].payload.json
360353

361-
invalid_keys = []
362-
for key in check_in_event.keys():
363-
if key not in valid_keys:
364-
invalid_keys.append(key)
354+
invalid_keys = []
355+
for key in check_in_event.keys():
356+
if key not in valid_keys:
357+
invalid_keys.append(key)
365358

366-
assert len(invalid_keys) == 0, "Unexpected keys found in checkin: {}".format(
367-
invalid_keys
368-
)
359+
assert len(invalid_keys) == 0, "Unexpected keys found in checkin: {}".format(
360+
invalid_keys
361+
)
369362

370363

371364
@pytest.mark.asyncio

0 commit comments

Comments
 (0)