Skip to content

Commit bc58bcf

Browse files
authored
feat: add MERGIFY_TRACEPARENT support (#148)
This allows the CI to propagate the job/jobstep span context to pytest-mergify to link them together. Fixes MRGFY-4951 Depends-On: #147
1 parent bdec192 commit bc58bcf

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

pytest_mergify/__init__.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import _pytest.terminal
1616
import opentelemetry.trace
1717
from opentelemetry.semconv.trace import SpanAttributes
18+
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
1819

1920
from pytest_mergify import utils
2021
from pytest_mergify.tracer import MergifyTracer
@@ -86,11 +87,18 @@ def tracer(self) -> typing.Optional[opentelemetry.trace.Tracer]:
8687

8788
def pytest_sessionstart(self, session: _pytest.main.Session) -> None:
8889
if self.tracer:
90+
traceparent = os.environ.get("MERGIFY_TRACEPARENT")
91+
if traceparent:
92+
ctx = TraceContextTextMapPropagator().extract(
93+
carrier={"traceparent": traceparent}
94+
)
95+
8996
self.session_span = self.tracer.start_span(
9097
"pytest session start",
9198
attributes={
9299
"test.scope": "session",
93100
},
101+
context=ctx if traceparent else None,
94102
)
95103
self.has_error = False
96104

tests/test_spans.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,34 @@ def test_span(
1818
}
1919

2020

21-
def test_session(
21+
def test_session_without_traceparent(
2222
pytester_with_spans: conftest.PytesterWithSpanT,
2323
) -> None:
2424
result, spans = pytester_with_spans()
2525
assert spans is not None
2626
s = spans["pytest session start"]
2727
assert s.attributes == {"test.scope": "session"}
2828
assert s.status.status_code == opentelemetry.trace.StatusCode.OK
29+
assert s.parent is None
30+
31+
32+
def test_session_with_traceparent(
33+
pytester_with_spans: conftest.PytesterWithSpanT,
34+
monkeypatch: pytest.MonkeyPatch,
35+
) -> None:
36+
monkeypatch.setenv(
37+
"MERGIFY_TRACEPARENT", "00-80e1afed08e019fc1110464cfa66635c-7a085853722dc6d2-01"
38+
)
39+
40+
result, spans = pytester_with_spans()
41+
assert spans is not None
42+
s = spans["pytest session start"]
43+
assert s.attributes == {"test.scope": "session"}
44+
assert s.status.status_code == opentelemetry.trace.StatusCode.OK
45+
assert s.parent is not None
46+
assert s.context.trace_id == 0x80E1AFED08E019FC1110464CFA66635C
47+
assert s.parent.trace_id == 0x80E1AFED08E019FC1110464CFA66635C
48+
assert s.parent.span_id == 0x7A085853722DC6D2
2949

3050

3151
def test_session_fail(

0 commit comments

Comments
 (0)