Skip to main content

pytest-otel-capture

Capture and inspect OpenTelemetry logs, spans, and metrics in Python tests with less selector and inspection boilerplate. Requires Python 3.12 or newer.

pip install pytest-otel-capture

This first release is a helper library, not an auto-loaded pytest plugin. Your fixture owns SDK providers and instrumentation; no application framework, exporter backend, or pytest runtime dependency is required.

from opentelemetry.sdk import trace
import pytest_otel_capture as capture

collected = capture.OTelMocker(
    capture.InMemoryLogRecordExporter(),
    capture.InMemorySpanExporter(),
    capture.InMemoryMetricReader(),
)
provider = trace.TracerProvider()
provider.add_span_processor(collected.span_processor)
try:
    with provider.get_tracer("example").start_as_current_span("work"):
        pass
    span = capture.get_span(collected.get_finished_spans(), "work")
    assert span is not None
    assert span.scope.name == "example"
finally:
    provider.shutdown()
    collected.log_processor.shutdown()
    collected.metric_reader.shutdown()

This captures telemetry accepted by a local SDK exporter/reader. It does not prove what a collector or remote backend receives: batching, OTLP serialization, collector transforms, and remote delivery need their own integration tests. Compared with direct SDK in-memory exporters/readers, this package adds atomic span/log drains, wrappers, and selectors—not provider configuration, instrumentation, or lifecycle management.

See behavioral test examples for an application-owned fixture, capture downstream of an application processor, and non-vacuous sensitive-marker checks.

Capture ownership and selectors

Inject span_processor into a TracerProvider, log_processor into a LoggerProvider, and metric_reader into a MeterProvider. Shut down each provider in your fixture's finally block. Local SDK providers avoid changing the process-global providers and separate capture destinations; they do not finish application work or remove other process-global state.

  • get_finished_spans() and get_finished_logs() drain their exporters. Each drain atomically removes its returned batch. Concurrent emissions fall in that batch or remain for a later drain; a drain does not wait for active spans, batch processors, threads, or async tasks. Do not independently clear or shut down the exporters while capturing. Atomic drains use SDK-private storage and locks, covered by the supported-version tests; custom exporter storage is unsupported.
  • get_metrics_data() collects a metric snapshot; it does not clear instruments.
  • find_spans, find_logs, and find_metrics return all matches. Attribute matching is a subset match; scope matches the instrumentation scope name.
  • get_span, get_log, and get_metric return None for no match and raise ValueError for ambiguous matches.
  • latest_metric_data returns the selected metric's last data point and checks its type. Attribute filtering selects the metric, not an individual data point. It is deprecated, with its behavior preserved until a future breaking release. Use get_metric_point to select the actual point by attributes (None for no match, ValueError for ambiguity), or find_metric_points for all matching points across metrics. Point sequence order does not imply chronological order.
  • assert_trace_id and assert_trace_header check trace identity. The header helper checks only the version/trace-ID prefix, not full W3C header validity. Neither helper proves propagation or parentage. For relationships, inspect parent_span_id, links, and log trace_id/span_id. Events include SDK exception attributes. readable_span, log_data, and metric metric retain access to underlying SDK data; log_data is untyped to also accept structural records. SDK log IDs are zero when uncorrelated; structural records without correlation fields return None.

Global state and lifecycle

Prefer designing your tests so OpenTelemetry's global state is not a problem, for example by injecting local providers. That is not always practical. For those cases, reset_otel_once() remains a private, test-only escape hatch that may enable sequential tests to replace global trace/metric providers. OTelMocker's legacy context manager calls it on exit; direct object use does not change globals.

This helper only re-arms trace/metric setters. Existing providers remain installed until replaced; logging's separate guard is not reset. It does not restore providers, rebind cached tracers/meters/loggers, remove handlers or instrumentors, or finish work. It deliberately does less than upstream's internal test resets, which also clear provider references and replace proxies. Neither is a supported runtime reset API, and upstream discourages using its test utilities externally.

Your fixture must finish and join telemetry-producing tasks/threads, force-flush any application-owned batch processors before final assertions, remove its logging handlers, uninstrument its instrumentors, and shut down the providers it owns. Do not shut down providers owned by another fixture or the application. Drain before shutdown when asserting captured records. Metrics have their own collection timing, below.

An active span can end after a drain and appear in a later drain. A tracer still bound to an old local provider sends to that provider, not the next test's capture; shutting down that provider early may lose the late emission. Local providers isolate capture destinations, not unfinished work or ambient current-span context. Finish work and exit span contexts before teardown. Global overrides require sequential tests with no surviving producers; xdist separates workers, not tests within a worker. Use fresh processes when stronger global-state isolation is required.

Metric snapshots

get_metrics_data() asks the reader to collect now, including invoking observable instrument callbacks. It is not a drain: instruments remain registered and callbacks run again on subsequent collections. Ensure application updates have finished before collecting, and use deterministic callbacks in tests.

The default reader reports cumulative counter values; a reader configured for delta temporality reports changes since its previous collection. Histograms expose aggregated counts, sums, and buckets, not individual measurements. Multiple attribute sets produce multiple points, not successive versions of one point. Inspect the SDK point type and attributes; use get_metric_point only when exactly one point should match, and find_metric_points or metric.data.data_points when all points matter. Inspect SDK aggregation temporality and configure reader preferences/views explicitly when those are part of the behavior under test.

Compatibility

The flake tests installed packages on Python 3.12, 3.13, and 3.14 against the oldest and latest supported OpenTelemetry versions. Exact pins live in the otel-minimum and otel-latest dependency groups in pyproject.toml:

OTel API/SDK Logging instrumentation
1.43.0 0.64b0
Latest 1.x Matching release

The minimum-version lane stays fixed. Renovate groups routine updates to the latest SDK and logging instrumentation, including new minor versions. The SDK selects its exact matching API; dependency groups do not pin the API independently. Intermediate versions need a specific workaround or behavior change to justify a regression lane; none currently require one. Security updates retain the shared Renovate policy.

Runtime dependencies allow >=1.43,<2 so consumers can install compatible security updates, including 1.45.2. The logging instrumentation package is used only in tests; the development shell uses the latest lane. The minimum pair remains for compatibility testing, not as a recommended version. API versions before 1.45.1 are affected by the tracestate parsing vulnerability (GHSA-xcq7-p3pf-p88h); passing compatibility tests does not make those versions security-recommended. All pairs are pinned in the same lockfile using conflicting dependency groups. Each flake check verifies the selected Python, SDK, and instrumentation versions and imports the installed package, not the source tree. Other SDK minors, instrumentation combinations, free-threaded Python builds, and platforms other than Linux are not covered by this matrix. Private exporter storage and reset internals require compatibility testing as new versions are adopted. Framework-specific fixtures stay in the application.

Development

nix develop
pytest -q
basedpyright
nix fmt
nix flake check
nix build

nix flake check runs the full compatibility matrix, including tests, strict typing, and distribution-content checks. CI and releases use this same command. To run one combination without entering a shell:

nix build .#checks.x86_64-linux.python313-otel-latest

The checks use Nix-built Python interpreters and locked dependencies, without network access during test execution or downloading generic Linux Python binaries. tests remains an alias for the Python 3.12/minimum-version check (python312-otel-minimum).

See RELEASING.md for repository setup and PyPI trusted publishing.

License

Licensed under the Apache License 2.0.

Metadata

Release files for pytest-otel-capture 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pytest-otel-capture 0.2.0
File Size Uploaded Provenance Actions
pytest_otel_capture-0.2.0.tar.gz 75.6 kB With provenance Details for pytest_otel_capture-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pytest-otel-capture 0.2.0
File Interpreter ABI Platform Actions
pytest_otel_capture-0.2.0-py3-none-any.whl Python 3 none any Details for pytest_otel_capture-0.2.0-py3-none-any.whl

Total release size: 90.7 kB

Release files / pytest_otel_capture-0.2.0.tar.gz

Download URL pytest_otel_capture-0.2.0.tar.gz
Size 75.6 kB
Tags Source
SHA-256 checksum
How to use checksums
675d3b207a6a016e231e70c3f44a62bfa3acfdbe309267525cbddad7c6c6aa3b
BLAKE2b-256 checksum
How to use checksums
84c44ee02f6f48140d7a02caf4d570405390de26ee42726226572841b4aacaa8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Release files / pytest_otel_capture-0.2.0-py3-none-any.whl

Download URL pytest_otel_capture-0.2.0-py3-none-any.whl
Size 15.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
b065c17c7461859edd9f2ae0b73c4380c0015a28e166ef9ffcfe91ed5ef622ff
BLAKE2b-256 checksum
How to use checksums
fdb1c1c249da1b105c5e50d747d1fa76a3e2459c63c7a4a6ed93441b61f9eeca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

Security for pytest-otel-capture 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for pytest_otel_capture-0.2.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 20, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page