|
| 1 | +import logging |
| 2 | + |
| 3 | +from app.rag import tracing |
| 4 | + |
| 5 | + |
| 6 | +def test_trace_function_uses_metadata_factory(monkeypatch): |
| 7 | + captured = {} |
| 8 | + |
| 9 | + def fake_trace_call(name, fn, *args, run_type, metadata, **kwargs): |
| 10 | + captured.update(name=name, run_type=run_type, metadata=metadata) |
| 11 | + return fn(*args, **kwargs) |
| 12 | + |
| 13 | + monkeypatch.setattr(tracing, "trace_call", fake_trace_call) |
| 14 | + |
| 15 | + @tracing.trace_function( |
| 16 | + "answer-question", |
| 17 | + metadata_factory=lambda value: {"value": value}, |
| 18 | + ) |
| 19 | + def decorated(value): |
| 20 | + return value.upper() |
| 21 | + |
| 22 | + assert decorated("hello") == "HELLO" |
| 23 | + assert captured == { |
| 24 | + "name": "answer-question", |
| 25 | + "run_type": "chain", |
| 26 | + "metadata": {"value": "hello"}, |
| 27 | + } |
| 28 | + |
| 29 | + |
| 30 | +def test_trace_function_shields_metadata_factory_exceptions(monkeypatch, caplog): |
| 31 | + captured = {} |
| 32 | + |
| 33 | + def fake_trace_call(name, fn, *args, run_type, metadata, **kwargs): |
| 34 | + captured["metadata"] = metadata |
| 35 | + return fn(*args, **kwargs) |
| 36 | + |
| 37 | + def failing_metadata_factory(value): |
| 38 | + raise KeyError(value) |
| 39 | + |
| 40 | + monkeypatch.setattr(tracing, "trace_call", fake_trace_call) |
| 41 | + |
| 42 | + @tracing.trace_function( |
| 43 | + "answer-question", |
| 44 | + metadata_factory=failing_metadata_factory, |
| 45 | + ) |
| 46 | + def decorated(value): |
| 47 | + return value.upper() |
| 48 | + |
| 49 | + with caplog.at_level(logging.WARNING, logger=tracing.__name__): |
| 50 | + assert decorated("hello") == "HELLO" |
| 51 | + |
| 52 | + assert captured["metadata"] == {} |
| 53 | + assert "Metadata factory failed for trace 'answer-question'" in caplog.text |
| 54 | + assert "KeyError: 'hello'" in caplog.text |
0 commit comments