test_event.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import json
  2. import pytest
  3. from pynecone import event
  4. from pynecone.event import Event, EventHandler, EventSpec
  5. from pynecone.var import Var
  6. def make_var(value) -> Var:
  7. """Make a variable.
  8. Args:
  9. value: The value of the var.
  10. Returns:
  11. The var.
  12. """
  13. var = Var.create(value)
  14. assert var is not None
  15. return var
  16. def test_create_event():
  17. """Test creating an event."""
  18. event = Event(token="token", name="state.do_thing", payload={"arg": "value"})
  19. assert event.token == "token"
  20. assert event.name == "state.do_thing"
  21. assert event.payload == {"arg": "value"}
  22. def test_call_event_handler():
  23. """Test that calling an event handler creates an event spec."""
  24. def test_fn():
  25. pass
  26. def test_fn_with_args(_, arg1, arg2):
  27. pass
  28. handler = EventHandler(fn=test_fn)
  29. event_spec = handler()
  30. assert event_spec.handler == handler
  31. assert event_spec.local_args == ()
  32. assert event_spec.args == ()
  33. handler = EventHandler(fn=test_fn_with_args)
  34. event_spec = handler(make_var("first"), make_var("second"))
  35. assert event_spec.handler == handler
  36. assert event_spec.local_args == ()
  37. assert event_spec.args == (("arg1", "first"), ("arg2", "second"))
  38. first, second = 123, "456"
  39. handler = EventHandler(fn=test_fn_with_args)
  40. event_spec = handler(first, second) # type: ignore
  41. assert event_spec.handler == handler
  42. assert event_spec.local_args == ()
  43. assert event_spec.args == (
  44. ("arg1", json.dumps(first, ensure_ascii=False)),
  45. ("arg2", json.dumps(second, ensure_ascii=False)),
  46. )
  47. handler = EventHandler(fn=test_fn_with_args)
  48. with pytest.raises(TypeError):
  49. handler(test_fn) # type: ignore
  50. def test_event_redirect():
  51. """Test the event redirect function."""
  52. spec = event.redirect("/path")
  53. assert isinstance(spec, EventSpec)
  54. assert spec.handler.fn.__qualname__ == "_redirect"
  55. assert spec.args == (("path", "/path"),)
  56. def test_event_console_log():
  57. """Test the event console log function."""
  58. spec = event.console_log("message")
  59. assert isinstance(spec, EventSpec)
  60. assert spec.handler.fn.__qualname__ == "_console"
  61. assert spec.args == (("message", "message"),)
  62. def test_event_window_alert():
  63. """Test the event window alert function."""
  64. spec = event.window_alert("message")
  65. assert isinstance(spec, EventSpec)
  66. assert spec.handler.fn.__qualname__ == "_alert"
  67. assert spec.args == (("message", "message"),)