"""Tests for metrics_lib. Run: .venv\\Scripts\\python.exe pipeline\\test_metrics_lib.py
Pytest-compatible (test_* functions) AND runnable as a script with a
non-zero exit code on failure.
"""
import sys
import os
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from metrics_lib import (
parse_calls,
normalize_value,
canon_call,
canon_calls,
categorize,
failure_bucket,
)
def _assistant(content="hi", tool_calls=None):
m = {"role": "assistant", "content": content}
if tool_calls is not None:
m["tool_calls"] = tool_calls
return m
def _tool(name, props):
return {"function": {"name": name, "parameters": {"type": "object", "properties": props}}}
# ---------------- parse_calls ----------------
def test_xml_single():
calls = parse_calls('Paris')
assert calls == [{"name": "get_weather", "arguments": {"city": "Paris"}}], calls
def test_xml_multiple():
text = ('1 '
'some prose '
'23')
calls = parse_calls(text)
assert len(calls) == 2, calls
assert calls[0]["name"] == "a" and calls[1]["name"] == "b"
assert calls[1]["arguments"] == {"y": "2", "z": "3"}
def test_xml_multiline_param():
text = 'line one\nline two\nline three'
calls = parse_calls(text)
assert calls[0]["arguments"]["query"] == "line one\nline two\nline three", calls
def test_xml_cdata():
text = ' 1 {"a": 1}]]>'
calls = parse_calls(text)
assert calls[0]["arguments"]["code"] == 'if x < 3 && y > 1 {"a": 1}', calls
def test_xml_single_quotes():
calls = parse_calls("v")
assert calls == [{"name": "f", "arguments": {"k": "v"}}], calls
def test_json_array():
calls = parse_calls('[{"name": "a", "arguments": {"x": 1}}, {"name": "b", "arguments": {}}]')
assert calls == [{"name": "a", "arguments": {"x": 1}}, {"name": "b", "arguments": {}}], calls
def test_json_tool_calls_object():
calls = parse_calls('{"tool_calls": [{"name": "a", "arguments": {"x": 1}}]}')
assert calls == [{"name": "a", "arguments": {"x": 1}}], calls
def test_json_openai_wrapper():
text = ('{"role": "assistant", "tool_calls": '
'[{"id": "1", "type": "function", "function": {"name": "a", "arguments": "{\\"x\\": 1}"}}]}')
calls = parse_calls(text)
assert calls == [{"name": "a", "arguments": {"x": 1}}], calls
def test_json_single_object():
calls = parse_calls('{"name": "solo", "arguments": {"k": "v"}}')
assert calls == [{"name": "solo", "arguments": {"k": "v"}}], calls
def test_json_args_string():
calls = parse_calls('{"name": "a", "arguments": "{\\"x\\": 2}"}')
assert calls == [{"name": "a", "arguments": {"x": 2}}], calls
def test_parse_empty():
assert parse_calls("") == []
assert parse_calls("no calls here, just prose") == []
# ---------------- normalize_value ----------------
def test_norm_true_variants():
assert normalize_value(True) == ("bool", True)
assert normalize_value("true") == ("bool", True)
assert normalize_value("True") == ("bool", True)
assert normalize_value("TRUE") == ("bool", True)
assert normalize_value("false") == ("bool", False)
assert normalize_value(False) == ("bool", False)
def test_norm_numeric_strings():
assert normalize_value("1") == normalize_value(1) == normalize_value("1.0") == ("num", 1.0)
assert normalize_value(1.5) == ("num", 1.5)
assert normalize_value("[1, 2]") == ("list", (("num", 1.0), ("num", 2.0)))
assert normalize_value([1, 2]) == ("list", (("num", 1.0), ("num", 2.0)))
def test_norm_bool_is_not_num():
assert normalize_value(True) != normalize_value(1)
assert normalize_value(True)[0] == "bool" and normalize_value(1)[0] == "num"
def test_norm_dict_and_none():
assert normalize_value({"b": 1, "a": "x"}) == (
"dict", (("a", ("str", "x")), ("b", ("num", 1.0))))
assert normalize_value("null") == ("none", None)
assert normalize_value(None) == ("none", None)
assert normalize_value("Paris") == ("str", "Paris")
def test_canon_sort_and_coercion():
c1 = canon_call({"name": "f", "arguments": {"b": "1", "a": 2}})
c2 = canon_call({"name": "f", "arguments": {"a": "2", "b": 1}})
assert c1 == c2
assert canon_calls([{"name": "b", "arguments": {}}]) > canon_calls([{"name": "a", "arguments": {}}])
assert canon_calls([]) == []
# ---------------- failure_bucket ----------------
def test_bucket_ok():
exp = [{"name": "a", "arguments": {"x": 1}}]
pred = [{"name": "a", "arguments": {"x": "1"}}] # typed-equal after coercion
assert failure_bucket(exp, pred, "raw") == "ok"
assert failure_bucket([], [], "nothing") == "ok"
def test_bucket_unparsed():
exp = [{"name": "a", "arguments": {}}]
assert failure_bucket(exp, [], 'I will call now') == "unparsed"
assert failure_bucket(exp, [], "using tool_call id=1 ...") == "unparsed"
def test_bucket_no_call():
exp = [{"name": "a", "arguments": {}}]
assert failure_bucket(exp, [], "plain text, no attempt") == "no_call"
def test_bucket_spurious():
assert failure_bucket([], [{"name": "a", "arguments": {}}], "raw") == "spurious_call"
def test_bucket_wrong_tool():
exp = [{"name": "a", "arguments": {}}]
assert failure_bucket(exp, [{"name": "b", "arguments": {}}], "raw") == "wrong_tool"
exp2 = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
pred2 = [{"name": "a", "arguments": {}}, {"name": "c", "arguments": {}}]
assert failure_bucket(exp2, pred2, "raw") == "wrong_tool"
def test_bucket_missing_extra():
exp = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
assert failure_bucket(exp, [{"name": "a", "arguments": {}}], "raw") == "missing_call"
assert failure_bucket([{"name": "a", "arguments": {}}], exp, "raw") == "extra_call"
def test_bucket_arg_mismatch():
exp = [{"name": "a", "arguments": {"city": "Paris"}}]
assert failure_bucket(exp, [{"name": "a", "arguments": {"city": "London"}}], "raw") == "arg_mismatch"
assert failure_bucket(exp, [{"name": "a", "arguments": {"town": "Paris"}}], "raw") == "arg_mismatch"
def test_bucket_value_typing():
exp = [{"name": "a", "arguments": {"city": "Paris"}}]
assert failure_bucket(exp, [{"name": "a", "arguments": {"city": "paris"}}], "raw") == "value_typing"
# ---------------- categorize ----------------
def test_cat_abstention():
row = {"tools": [], "messages": [{"role": "user", "content": "hi"}, _assistant("no tools")]}
assert categorize(row) == "abstention"
def test_cat_multi():
tc = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
row = {"tools": [], "messages": [{"role": "user", "content": "q"}, _assistant("x", tc)]}
assert categorize(row) == "multi_call"
def test_cat_nested_schema():
row = {"tools": [_tool("f", {"obj": {"type": "object"}})],
"messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f", "arguments": {"obj": "s"}}])]}
assert categorize(row) == "nested_args"
def test_cat_nested_values():
row = {"tools": [_tool("f", {"s": {"type": "string"}})],
"messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f", "arguments": {"s": {"deep": 1}}}])]}
assert categorize(row) == "nested_args"
def test_cat_enum():
row = {"tools": [_tool("f", {"c": {"type": "string", "enum": ["r", "g"]}})],
"messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f", "arguments": {"c": "r"}}])]}
assert categorize(row) == "enum_args"
def test_cat_long_and_single():
tools = [_tool("f%d" % i, {"s": {"type": "string"}}) for i in range(10)]
row = {"tools": tools, "messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f0", "arguments": {}}])]}
assert categorize(row) == "long_tools"
row2 = {"tools": [_tool("f", {"s": {"type": "string"}})],
"messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f", "arguments": {"s": "v"}}])]}
assert categorize(row2) == "single_call"
def test_cat_priority():
# abstention beats multi_call history: earlier assistant had 2 calls, last has none
tc = [{"name": "a", "arguments": {}}, {"name": "b", "arguments": {}}]
row = {"tools": [], "messages": [{"role": "user", "content": "q"},
_assistant("x", tc),
{"role": "user", "content": "q2"},
_assistant("none")] }
assert categorize(row) == "abstention"
# multi beats nested schema
row = {"tools": [_tool("f", {"o": {"type": "object"}})],
"messages": [{"role": "user", "content": "q"}, _assistant("x", tc)]}
assert categorize(row) == "multi_call"
# nested beats enum
row = {"tools": [_tool("f", {"o": {"type": "object"}, "c": {"type": "string", "enum": ["a"]}})],
"messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f", "arguments": {"o": "v", "c": "a"}}])]}
assert categorize(row) == "nested_args"
# enum beats long_tools
tools = [_tool("f%d" % i, {"s": {"type": "string"}}) for i in range(10)]
tools[0]["function"]["parameters"]["properties"]["s"] = {"type": "string", "enum": ["a"]}
row = {"tools": tools, "messages": [{"role": "user", "content": "q"},
_assistant("x", [{"name": "f0", "arguments": {"s": "a"}}])]}
assert categorize(row) == "enum_args"
def main():
tests = sorted([(k, v) for k, v in sorted(globals().items())
if k.startswith("test_") and callable(v)])
failed = 0
for name, fn in tests:
try:
fn()
except Exception as e:
failed += 1
print("FAIL %s: %r" % (name, e))
else:
print("PASS %s" % name)
print("%d passed, %d failed, %d total" % (len(tests) - failed, failed, len(tests)))
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(main())