# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """The ContextVar that lets a fetcher report a timing it was never asked for.""" from __future__ import annotations import pytest from signal_bot.analytics import probe def test_nothing_is_probing_by_default() -> None: """The var's default is what every no-op branch below tests against.""" assert probe.CURRENT.get() is None def test_notes_outside_a_probe_are_dropped() -> None: """The whole point: a caller never asks whether it is being measured. ``http_client`` and ``context`` call these unconditionally, and the offline end-to-end run drives both with no dispatcher above them. """ probe.note_send(5) probe.note_upstream("example.test", 200, 5) probe.note_item("Q1") assert probe.CURRENT.get() is None def test_a_probe_collects_what_ran_under_it() -> None: """One invocation's notes, from three different layers.""" with probe.probing() as active: probe.note_send(120) probe.note_send(80) probe.note_upstream("api.example.test", 200, 40) probe.note_upstream("cdn.example.test", 500, 15) probe.note_item("Q42") assert active.send_ms == 200 assert active.item_id == "Q42" assert [(call.host, call.status, call.ms) for call in active.calls] == [ ("api.example.test", 200, 40), ("cdn.example.test", 500, 15), ] def _fail() -> None: """A handler that raises, in its own function so the raise is not inline.""" raise RuntimeError def test_the_probe_is_closed_even_when_the_handler_raises() -> None: """A command that fails is still a command whose cost we wanted.""" seen: list[probe.Probe] = [] def run() -> None: with probe.probing() as active: seen.append(active) probe.note_upstream("api.example.test", probe.NO_RESPONSE, 30) _fail() with pytest.raises(RuntimeError): run() assert probe.CURRENT.get() is None assert len(seen[0].calls) == 1 def test_probes_do_not_leak_into_each_other() -> None: """reset(token), not set(None) -- two invocations in a row must not merge.""" with probe.probing() as first: probe.note_send(10) with probe.probing() as second: probe.note_send(20) assert first.send_ms == 10 assert second.send_ms == 20 def test_a_nested_probe_restores_the_outer_one() -> None: """Nesting is not expected, but a token reset must survive it if it happens.""" with probe.probing() as outer: with probe.probing() as inner: probe.note_send(3) probe.note_send(7) assert inner.send_ms == 3 assert outer.send_ms == 7