Skip to content

Commit e952020

Browse files
authored
Added top level API to get current span (#1954)
* Added top level API to get current span
1 parent 3e67535 commit e952020

File tree

3 files changed

+53
-0
lines changed

3 files changed

+53
-0
lines changed

sentry_sdk/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"set_user",
3333
"set_level",
3434
"set_measurement",
35+
"get_current_span",
3536
]
3637

3738
# Initialize the debug support after everything is loaded

sentry_sdk/api.py

+13
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ def overload(x):
5353
"set_user",
5454
"set_level",
5555
"set_measurement",
56+
"get_current_span",
5657
]
5758

5859

@@ -228,3 +229,15 @@ def set_measurement(name, value, unit=""):
228229
transaction = Hub.current.scope.transaction
229230
if transaction is not None:
230231
transaction.set_measurement(name, value, unit)
232+
233+
234+
def get_current_span(hub=None):
235+
# type: (Optional[Hub]) -> Optional[Span]
236+
"""
237+
Returns the currently active span if there is one running, otherwise `None`
238+
"""
239+
if hub is None:
240+
hub = Hub.current
241+
242+
current_span = hub.scope.span
243+
return current_span

tests/test_api.py

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import mock
2+
3+
from sentry_sdk import (
4+
configure_scope,
5+
get_current_span,
6+
start_transaction,
7+
)
8+
9+
10+
def test_get_current_span():
11+
fake_hub = mock.MagicMock()
12+
fake_hub.scope = mock.MagicMock()
13+
14+
fake_hub.scope.span = mock.MagicMock()
15+
assert get_current_span(fake_hub) == fake_hub.scope.span
16+
17+
fake_hub.scope.span = None
18+
assert get_current_span(fake_hub) is None
19+
20+
21+
def test_get_current_span_default_hub(sentry_init):
22+
sentry_init()
23+
24+
assert get_current_span() is None
25+
26+
with configure_scope() as scope:
27+
fake_span = mock.MagicMock()
28+
scope.span = fake_span
29+
30+
assert get_current_span() == fake_span
31+
32+
33+
def test_get_current_span_default_hub_with_transaction(sentry_init):
34+
sentry_init()
35+
36+
assert get_current_span() is None
37+
38+
with start_transaction() as new_transaction:
39+
assert get_current_span() == new_transaction

0 commit comments

Comments
 (0)