test_core.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """Tests for lambdagent core: Term, Context, TraceEntry."""
  2. import pytest
  3. from lambdagent.core import Term, Context, TraceEntry, LambdagentError, UnboundVariable
  4. class DummyTerm(Term):
  5. def apply(self, input, ctx):
  6. ctx.log(self._name, self._trace_id, input, f"echo:{input}", 1.0)
  7. return f"echo:{input}"
  8. def test_term_call():
  9. t = DummyTerm("test")
  10. assert t("hello") == "echo:hello"
  11. def test_term_compose():
  12. a = DummyTerm("a")
  13. b = DummyTerm("b")
  14. pipe = a >> b
  15. assert pipe("x") == "echo:echo:x"
  16. def test_term_par():
  17. a = DummyTerm("a")
  18. b = DummyTerm("b")
  19. par = a | b
  20. result = par("x")
  21. assert result == ("echo:x", "echo:x")
  22. def test_context_trace():
  23. ctx = Context()
  24. t = DummyTerm("t")
  25. t.apply("in", ctx)
  26. assert len(ctx.trace) == 1
  27. assert ctx.trace[0].term_name == "t"
  28. assert ctx.trace[0].input == "in"
  29. assert ctx.trace[0].output == "echo:in"
  30. def test_context_extend():
  31. ctx = Context(bindings={"x": 1})
  32. child = ctx.extend(y=2)
  33. assert child.lookup("x") == 1
  34. assert child.lookup("y") == 2
  35. def test_context_unbound():
  36. ctx = Context()
  37. with pytest.raises(UnboundVariable):
  38. ctx.lookup("missing")
  39. def test_context_memory():
  40. ctx = Context(memory={"key": "val"})
  41. assert ctx.memory["key"] == "val"