test_evaluation_context.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. from typing import Any
  2. import pytest
  3. from flagpole.evaluation_context import ContextBuilder, EvaluationContextDict
  4. class TestEvaluationContext:
  5. pass
  6. class TestContextBuilder:
  7. def test_empty_context_builder(self):
  8. context_builder = ContextBuilder()
  9. context = context_builder.build()
  10. assert context.size() == 0
  11. def test_static_transformer(self):
  12. def static_transformer(_data: dict[str, Any]) -> dict[str, Any]:
  13. return dict(foo="bar", baz=1)
  14. eval_context = ContextBuilder().add_context_transformer(static_transformer).build()
  15. assert eval_context.size() == 2
  16. assert eval_context.get("foo") == "bar"
  17. assert eval_context.get("baz") == 1
  18. def test_transformer_with_data(self):
  19. def transformer_with_data(data: dict[str, Any]) -> dict[str, Any]:
  20. return dict(foo="bar", baz=data.get("baz"))
  21. eval_context = (
  22. ContextBuilder().add_context_transformer(transformer_with_data).build({"baz": 2})
  23. )
  24. assert eval_context.size() == 2
  25. assert eval_context.get("foo") == "bar"
  26. assert eval_context.get("baz") == 2
  27. def test_multiple_context_transformers(self):
  28. def transformer_one(data: dict[str, Any]) -> dict[str, Any]:
  29. return dict(foo="overwrite_me", baz=2, buzz=data.get("buzz"))
  30. def transformer_two(_data: dict[str, Any]) -> dict[str, Any]:
  31. return dict(foo="bar")
  32. eval_context = (
  33. ContextBuilder()
  34. .add_context_transformer(transformer_one)
  35. .add_context_transformer(transformer_two)
  36. .build({"foo": "bar", "buzz": {1, 2, 3}})
  37. )
  38. assert eval_context.size() == 3
  39. assert eval_context.get("foo") == "bar"
  40. assert eval_context.get("baz") == 2
  41. assert eval_context.get("buzz") == {1, 2, 3}
  42. def test_with_exception_handler(self):
  43. exc_message = "oh noooooo"
  44. def broken_transformer(_data: dict[str, Any]) -> EvaluationContextDict:
  45. raise Exception(exc_message)
  46. context_builder = ContextBuilder().add_context_transformer(broken_transformer)
  47. with pytest.raises(Exception) as exc:
  48. context_builder.build(dict())
  49. assert exc.match(exc_message)
  50. # Ensure builder doesn't raise an exception
  51. context_builder.add_exception_handler(lambda _exc: None)
  52. context_builder.build(dict())
  53. with pytest.raises(Exception):
  54. context_builder.add_exception_handler(lambda _exc: None)