Skip to content

Commit

Permalink
Added top level API to get current span (#1954)
Browse files Browse the repository at this point in the history
* Added top level API to get current span
  • Loading branch information
antonpirker authored Mar 15, 2023
1 parent 3e67535 commit e952020
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions sentry_sdk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
"set_user",
"set_level",
"set_measurement",
"get_current_span",
]

# Initialize the debug support after everything is loaded
Expand Down
13 changes: 13 additions & 0 deletions sentry_sdk/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ def overload(x):
"set_user",
"set_level",
"set_measurement",
"get_current_span",
]


Expand Down Expand Up @@ -228,3 +229,15 @@ def set_measurement(name, value, unit=""):
transaction = Hub.current.scope.transaction
if transaction is not None:
transaction.set_measurement(name, value, unit)


def get_current_span(hub=None):
# type: (Optional[Hub]) -> Optional[Span]
"""
Returns the currently active span if there is one running, otherwise `None`
"""
if hub is None:
hub = Hub.current

current_span = hub.scope.span
return current_span
39 changes: 39 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import mock

from sentry_sdk import (
configure_scope,
get_current_span,
start_transaction,
)


def test_get_current_span():
fake_hub = mock.MagicMock()
fake_hub.scope = mock.MagicMock()

fake_hub.scope.span = mock.MagicMock()
assert get_current_span(fake_hub) == fake_hub.scope.span

fake_hub.scope.span = None
assert get_current_span(fake_hub) is None


def test_get_current_span_default_hub(sentry_init):
sentry_init()

assert get_current_span() is None

with configure_scope() as scope:
fake_span = mock.MagicMock()
scope.span = fake_span

assert get_current_span() == fake_span


def test_get_current_span_default_hub_with_transaction(sentry_init):
sentry_init()

assert get_current_span() is None

with start_transaction() as new_transaction:
assert get_current_span() == new_transaction

0 comments on commit e952020

Please sign in to comment.