test_extensions.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Tests for lambdagent extensions: Par, Route, Memory, Guard."""
  2. import pytest
  3. from lambdagent.core import Context, RouteError, ValidationError
  4. from lambdagent.primitives import Tool
  5. from lambdagent.extensions import Par, Route, Memory, Guard
  6. def t(name, fn):
  7. return Tool(name, fn)
  8. def test_par():
  9. a = t("x2", lambda x: int(x) * 2)
  10. b = t("x3", lambda x: int(x) * 3)
  11. p = Par(a, b)
  12. assert p("4") == (8, 12)
  13. def test_par_operator():
  14. a = t("a", lambda x: "A")
  15. b = t("b", lambda x: "B")
  16. c = t("c", lambda x: "C")
  17. p = a | b | c
  18. assert p("x") == ("A", "B", "C")
  19. def test_route():
  20. cls = t("cls", lambda x: "math" if "+" in x else "text")
  21. math_agent = t("math", lambda x: "math_result")
  22. text_agent = t("text", lambda x: "text_result")
  23. router = Route(cls, {"math": math_agent, "text": text_agent})
  24. assert router("1+1") == "math_result"
  25. assert router("hello") == "text_result"
  26. def test_route_default():
  27. cls = t("cls", lambda x: "unknown")
  28. default = t("default", lambda x: "default_result")
  29. router = Route(cls, {"a": t("a", lambda x: "A")}, default=default)
  30. assert router("x") == "default_result"
  31. def test_route_no_match():
  32. cls = t("cls", lambda x: "missing")
  33. router = Route(cls, {"a": t("a", lambda x: "A")})
  34. with pytest.raises(RouteError):
  35. router("x")
  36. def test_memory():
  37. agent = t("echo", lambda x: x)
  38. mem = Memory(agent, store={"user": "Alice"})
  39. result = mem("hello")
  40. assert "Alice" in result
  41. assert "hello" in result
  42. def test_memory_remember_forget():
  43. agent = t("echo", lambda x: x)
  44. mem = Memory(agent)
  45. mem.remember("k", "v")
  46. assert mem.store["k"] == "v"
  47. mem.forget("k")
  48. assert "k" not in mem.store
  49. def test_guard_pass():
  50. agent = t("gen", lambda x: "long enough output text here")
  51. g = Guard(agent, validator=lambda x: len(x) > 5)
  52. assert g("x") == "long enough output text here"
  53. def test_guard_fail():
  54. agent = t("gen", lambda x: "hi")
  55. g = Guard(agent, validator=lambda x: len(x) > 100, retry=1)
  56. with pytest.raises(ValidationError):
  57. g("x")
  58. def test_guard_on_fail():
  59. agent = t("gen", lambda x: "short")
  60. g = Guard(agent, validator=lambda x: len(x) > 100, retry=0, on_fail=lambda x: "fallback")
  61. assert g("x") == "fallback"