import json import threading import pytest import workflow_artifacts as a from workflow_diagnostics import LoggedProgress, StageTrace def records(capsys): return [json.loads(line[len("[workflow] "):]) for line in capsys.readouterr().out.splitlines() if line.startswith("[workflow] ")] def test_progress_forwarding_cache_hit_and_failure(capsys): calls = [] def callback(*args, **kwargs): calls.append((args, kwargs)) return "forwarded" def compute(): assert LoggedProgress(callback)(.2, desc="Viggle loading") == "forwarded" return ("completed",), [] assert a.cached("trace_test", [1], compute) == ("completed",) assert a.cached("trace_test", [1], lambda: pytest.fail("cache was ignored")) == ("completed",) assert calls == [((.2,), {"desc": "Viggle loading"})] seen = records(capsys) assert any(r["phase"] == "Viggle loading" for r in seen) assert any(r["phase"] == "cache_hit" for r in seen) assert len([r for r in seen if r["event"] == "finished"]) == 2 failure = RuntimeError("original exception") def fail(): raise failure with pytest.raises(RuntimeError) as exc: a.cached("trace_failure", [1], fail) assert exc.value is failure assert records(capsys)[-1]["event"] == "failed" assert a.cached("trace_failure", [1], lambda: (("retry",), [])) == ("retry",) def test_heartbeat_reports_wait_without_cancelling_worker(): emitted = threading.Event() rows = [] trace = StageTrace("held", interval=.01) def emit(event, **kwargs): rows.append((event, trace.phase)) if event == "heartbeat": emitted.set() trace.emit = emit with trace: assert emitted.wait(1) assert not trace.stopped.is_set() assert ("heartbeat", "waiting_for_execution_lock") in rows assert not trace.thread.is_alive()