test_hydrate_middleware.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. from typing import List
  2. import pytest
  3. from pynecone.app import App
  4. from pynecone.middleware.hydrate_middleware import HydrateMiddleware
  5. from pynecone.state import State
  6. class TestState(State):
  7. """A test state with no return in handler."""
  8. num: int = 0
  9. def test_handler(self):
  10. """Test handler."""
  11. self.num += 1
  12. class TestState2(State):
  13. """A test state with return in handler."""
  14. num: int = 0
  15. name: str
  16. def test_handler(self):
  17. """Test handler that calls another handler.
  18. Returns:
  19. Chain of EventHandlers
  20. """
  21. self.num += 1
  22. return self.change_name
  23. def change_name(self):
  24. """Test handler to change name."""
  25. self.name = "random"
  26. class TestState3(State):
  27. """A test state with async handler."""
  28. num: int = 0
  29. async def test_handler(self):
  30. """Test handler."""
  31. self.num += 1
  32. @pytest.mark.asyncio
  33. @pytest.mark.parametrize(
  34. "state, expected, event_fixture",
  35. [
  36. (TestState, {"test_state": {"num": 1}}, "event1"),
  37. (TestState2, {"test_state2": {"num": 1}}, "event2"),
  38. (TestState3, {"test_state3": {"num": 1}}, "event3"),
  39. ],
  40. )
  41. async def test_preprocess(state, request, event_fixture, expected):
  42. """Test that a state hydrate event is processed correctly.
  43. Args:
  44. state: state to process event
  45. request: pytest fixture request
  46. event_fixture: The event fixture(an Event)
  47. expected: expected delta
  48. """
  49. app = App(state=state, load_events={"index": state.test_handler})
  50. hydrate_middleware = HydrateMiddleware()
  51. result = await hydrate_middleware.preprocess(
  52. app=app, event=request.getfixturevalue(event_fixture), state=state()
  53. )
  54. assert isinstance(result, List)
  55. assert result[0].delta == expected
  56. @pytest.mark.asyncio
  57. async def test_preprocess_multiple_load_events(event1):
  58. """Test that a state hydrate event for multiple on-load events is processed correctly.
  59. Args:
  60. event1: an Event.
  61. """
  62. app = App(
  63. state=TestState,
  64. load_events={"index": [TestState.test_handler, TestState.test_handler]},
  65. )
  66. hydrate_middleware = HydrateMiddleware()
  67. result = await hydrate_middleware.preprocess(
  68. app=app, event=event1, state=TestState()
  69. )
  70. assert isinstance(result, List)
  71. assert result[0].delta == {"test_state": {"num": 1}}
  72. assert result[1].delta == {"test_state": {"num": 2}}