Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement defensive programming techniques for setting spans in ContextVars #2179

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion elasticapm/context/contextvars.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def set_span(self, span: "elasticapm.traces.Span") -> None:

The previously-activated span will be saved to be re-activated later.
"""
spans = self.elasticapm_spans_var.get()
spans: tuple = self.elasticapm_spans_var.get() or ()
self.elasticapm_spans_var.set(spans + (span,))

def unset_span(self, clear_all: bool = False) -> "elasticapm.traces.Span":
Expand Down
12 changes: 12 additions & 0 deletions tests/context/test_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,13 @@

import sys

import mock
import pytest

import elasticapm.context
from elasticapm.context.contextvars import ContextVarsContext
from elasticapm.context.threadlocal import ThreadLocalContext
from elasticapm.traces import Span


def test_execution_context_backing():
Expand Down Expand Up @@ -63,3 +66,12 @@ def test_execution_context_monkeypatched(monkeypatch):

# Should always use ThreadLocalContext when thread local is monkey patched
assert isinstance(execution_context, ThreadLocalContext)


def test_none_spans_should_not_raise_a_type_error_on_set_span():
context = ContextVarsContext()
context.elasticapm_spans_var.set(None)

context.set_span(mock.MagicMock(spec=Span))

assert context.get_span() is not None
Loading