test_primitives.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. """Tests for lambdagent primitives: Compose, If, Loop, Pair, Fst, Snd, Tool."""
  2. import pytest
  3. from lambdagent.core import Context
  4. from lambdagent.primitives import Compose, If, Loop, Pair, Fst, Snd, Tool
  5. def make_tool(name, fn):
  6. return Tool(name, fn)
  7. def test_tool_apply():
  8. t = make_tool("double", lambda x: int(x) * 2)
  9. assert t("3") == 6
  10. def test_tool_trace():
  11. ctx = Context()
  12. t = make_tool("inc", lambda x: int(x) + 1)
  13. t.apply("5", ctx)
  14. assert len(ctx.trace) == 1
  15. assert ctx.trace[0].output == 6
  16. def test_compose():
  17. a = make_tool("add1", lambda x: int(x) + 1)
  18. b = make_tool("mul2", lambda x: int(x) * 2)
  19. pipe = Compose(a, b)
  20. assert pipe("3") == 8 # (3+1)*2
  21. def test_compose_operator():
  22. a = make_tool("a", lambda x: x + "A")
  23. b = make_tool("b", lambda x: x + "B")
  24. c = make_tool("c", lambda x: x + "C")
  25. pipe = a >> b >> c
  26. assert pipe("") == "ABC"
  27. def test_if_truthy():
  28. t = make_tool("yes", lambda x: "YES")
  29. f = make_tool("no", lambda x: "NO")
  30. cond = If(lambda x: x == "go", t, f)
  31. assert cond("go") == "YES"
  32. assert cond("stop") == "NO"
  33. def test_if_term_cond():
  34. cond_term = make_tool("check", lambda x: "TRUE" if len(x) > 3 else "FALSE")
  35. t = make_tool("long", lambda x: "long")
  36. f = make_tool("short", lambda x: "short")
  37. branch = If(cond_term, t, f)
  38. assert branch("hello") == "long"
  39. assert branch("hi") == "short"
  40. def test_loop():
  41. counter = {"n": 0}
  42. def step(x):
  43. counter["n"] += 1
  44. return int(x) + 1
  45. body = make_tool("inc", step)
  46. loop = Loop(body, condition=lambda r, s: int(r) >= 5, max_steps=20)
  47. result = loop("0")
  48. assert result == 5
  49. assert counter["n"] == 5
  50. def test_loop_max_steps():
  51. body = make_tool("noop", lambda x: x)
  52. loop = Loop(body, condition=lambda r, s: False, max_steps=3)
  53. loop("x") # Should not infinite loop
  54. def test_pair():
  55. a = make_tool("upper", lambda x: x.upper())
  56. b = make_tool("lower", lambda x: x.lower())
  57. p = Pair(a, b)
  58. assert p("Hello") == ("HELLO", "hello")
  59. def test_fst_snd():
  60. assert Fst()(("a", "b")) == "a"
  61. assert Snd()(("a", "b")) == "b"