test_event.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. from typing import Callable, List
  2. import pytest
  3. from reflex.event import (
  4. Event,
  5. EventChain,
  6. EventHandler,
  7. EventSpec,
  8. call_event_handler,
  9. event,
  10. fix_events,
  11. )
  12. from reflex.state import BaseState
  13. from reflex.utils import format
  14. from reflex.vars.base import Field, LiteralVar, Var, field
  15. def make_var(value) -> Var:
  16. """Make a variable.
  17. Args:
  18. value: The value of the var.
  19. Returns:
  20. The var.
  21. """
  22. return Var(_js_expr=value)
  23. def test_create_event():
  24. """Test creating an event."""
  25. event = Event(token="token", name="state.do_thing", payload={"arg": "value"})
  26. assert event.token == "token"
  27. assert event.name == "state.do_thing"
  28. assert event.payload == {"arg": "value"}
  29. def test_call_event_handler():
  30. """Test that calling an event handler creates an event spec."""
  31. def test_fn():
  32. pass
  33. test_fn.__qualname__ = "test_fn"
  34. def test_fn_with_args(_, arg1, arg2):
  35. pass
  36. test_fn_with_args.__qualname__ = "test_fn_with_args"
  37. handler = EventHandler(fn=test_fn)
  38. event_spec = handler()
  39. assert event_spec.handler == handler
  40. assert event_spec.args == ()
  41. assert format.format_event(event_spec) == 'Event("test_fn", {})'
  42. handler = EventHandler(fn=test_fn_with_args)
  43. event_spec = handler(make_var("first"), make_var("second"))
  44. # Test passing vars as args.
  45. assert event_spec.handler == handler
  46. assert event_spec.args[0][0].equals(Var(_js_expr="arg1"))
  47. assert event_spec.args[0][1].equals(Var(_js_expr="first"))
  48. assert event_spec.args[1][0].equals(Var(_js_expr="arg2"))
  49. assert event_spec.args[1][1].equals(Var(_js_expr="second"))
  50. assert (
  51. format.format_event(event_spec)
  52. == 'Event("test_fn_with_args", {arg1:first,arg2:second})'
  53. )
  54. # Passing args as strings should format differently.
  55. event_spec = handler("first", "second") # type: ignore
  56. assert (
  57. format.format_event(event_spec)
  58. == 'Event("test_fn_with_args", {arg1:"first",arg2:"second"})'
  59. )
  60. first, second = 123, "456"
  61. handler = EventHandler(fn=test_fn_with_args)
  62. event_spec = handler(first, second) # type: ignore
  63. assert (
  64. format.format_event(event_spec)
  65. == 'Event("test_fn_with_args", {arg1:123,arg2:"456"})'
  66. )
  67. assert event_spec.handler == handler
  68. assert event_spec.args[0][0].equals(Var(_js_expr="arg1"))
  69. assert event_spec.args[0][1].equals(LiteralVar.create(first))
  70. assert event_spec.args[1][0].equals(Var(_js_expr="arg2"))
  71. assert event_spec.args[1][1].equals(LiteralVar.create(second))
  72. handler = EventHandler(fn=test_fn_with_args)
  73. with pytest.raises(TypeError):
  74. handler(test_fn) # type: ignore
  75. def test_call_event_handler_partial():
  76. """Calling an EventHandler with incomplete args returns an EventSpec that can be extended."""
  77. def test_fn_with_args(_, arg1, arg2):
  78. pass
  79. test_fn_with_args.__qualname__ = "test_fn_with_args"
  80. def spec(a2: Var[str]) -> List[Var[str]]:
  81. return [a2]
  82. handler = EventHandler(fn=test_fn_with_args)
  83. event_spec = handler(make_var("first"))
  84. event_spec2 = call_event_handler(event_spec, spec)
  85. assert event_spec.handler == handler
  86. assert len(event_spec.args) == 1
  87. assert event_spec.args[0][0].equals(Var(_js_expr="arg1"))
  88. assert event_spec.args[0][1].equals(Var(_js_expr="first"))
  89. assert format.format_event(event_spec) == 'Event("test_fn_with_args", {arg1:first})'
  90. assert event_spec2 is not event_spec
  91. assert event_spec2.handler == handler
  92. assert len(event_spec2.args) == 2
  93. assert event_spec2.args[0][0].equals(Var(_js_expr="arg1"))
  94. assert event_spec2.args[0][1].equals(Var(_js_expr="first"))
  95. assert event_spec2.args[1][0].equals(Var(_js_expr="arg2"))
  96. assert event_spec2.args[1][1].equals(Var(_js_expr="_a2", _var_type=str))
  97. assert (
  98. format.format_event(event_spec2)
  99. == 'Event("test_fn_with_args", {arg1:first,arg2:_a2})'
  100. )
  101. @pytest.mark.parametrize(
  102. ("arg1", "arg2"),
  103. (
  104. (1, 2),
  105. (1, "2"),
  106. ({"a": 1}, {"b": 2}),
  107. ),
  108. )
  109. def test_fix_events(arg1, arg2):
  110. """Test that chaining an event handler with args formats the payload correctly.
  111. Args:
  112. arg1: The first arg passed to the handler.
  113. arg2: The second arg passed to the handler.
  114. """
  115. def test_fn_with_args(_, arg1, arg2):
  116. pass
  117. test_fn_with_args.__qualname__ = "test_fn_with_args"
  118. handler = EventHandler(fn=test_fn_with_args)
  119. event_spec = handler(arg1, arg2)
  120. event = fix_events([event_spec], token="foo")[0]
  121. assert event.name == test_fn_with_args.__qualname__
  122. assert event.token == "foo"
  123. assert event.payload == {"arg1": arg1, "arg2": arg2}
  124. @pytest.mark.parametrize(
  125. "input,output",
  126. [
  127. (
  128. ("/path", None, None),
  129. 'Event("_redirect", {path:"/path",external:false,replace:false})',
  130. ),
  131. (
  132. ("/path", True, None),
  133. 'Event("_redirect", {path:"/path",external:true,replace:false})',
  134. ),
  135. (
  136. ("/path", False, None),
  137. 'Event("_redirect", {path:"/path",external:false,replace:false})',
  138. ),
  139. (
  140. (Var(_js_expr="path"), None, None),
  141. 'Event("_redirect", {path:path,external:false,replace:false})',
  142. ),
  143. (
  144. ("/path", None, True),
  145. 'Event("_redirect", {path:"/path",external:false,replace:true})',
  146. ),
  147. (
  148. ("/path", True, True),
  149. 'Event("_redirect", {path:"/path",external:true,replace:true})',
  150. ),
  151. ],
  152. )
  153. def test_event_redirect(input, output):
  154. """Test the event redirect function.
  155. Args:
  156. input: The input for running the test.
  157. output: The expected output to validate the test.
  158. """
  159. path, external, replace = input
  160. kwargs = {}
  161. if external is not None:
  162. kwargs["external"] = external
  163. if replace is not None:
  164. kwargs["replace"] = replace
  165. spec = event.redirect(path, **kwargs)
  166. assert isinstance(spec, EventSpec)
  167. assert spec.handler.fn.__qualname__ == "_redirect"
  168. # this asserts need comment about what it's testing (they fail with Var as input)
  169. # assert spec.args[0][0].equals(Var(_js_expr="path"))
  170. # assert spec.args[0][1].equals(Var(_js_expr="/path"))
  171. assert format.format_event(spec) == output
  172. def test_event_console_log():
  173. """Test the event console log function."""
  174. spec = event.console_log("message")
  175. assert isinstance(spec, EventSpec)
  176. assert spec.handler.fn.__qualname__ == "_call_function"
  177. assert spec.args[0][0].equals(Var(_js_expr="function"))
  178. assert spec.args[0][1].equals(
  179. Var('(() => ((console["log"]("message"))))', _var_type=Callable)
  180. )
  181. assert (
  182. format.format_event(spec)
  183. == 'Event("_call_function", {function:(() => ((console["log"]("message"))))})'
  184. )
  185. spec = event.console_log(Var(_js_expr="message"))
  186. assert (
  187. format.format_event(spec)
  188. == 'Event("_call_function", {function:(() => ((console["log"](message))))})'
  189. )
  190. def test_event_window_alert():
  191. """Test the event window alert function."""
  192. spec = event.window_alert("message")
  193. assert isinstance(spec, EventSpec)
  194. assert spec.handler.fn.__qualname__ == "_call_function"
  195. assert spec.args[0][0].equals(Var(_js_expr="function"))
  196. assert spec.args[0][1].equals(
  197. Var('(() => ((window["alert"]("message"))))', _var_type=Callable)
  198. )
  199. assert (
  200. format.format_event(spec)
  201. == 'Event("_call_function", {function:(() => ((window["alert"]("message"))))})'
  202. )
  203. spec = event.window_alert(Var(_js_expr="message"))
  204. assert (
  205. format.format_event(spec)
  206. == 'Event("_call_function", {function:(() => ((window["alert"](message))))})'
  207. )
  208. def test_set_focus():
  209. """Test the event set focus function."""
  210. spec = event.set_focus("input1")
  211. assert isinstance(spec, EventSpec)
  212. assert spec.handler.fn.__qualname__ == "_set_focus"
  213. assert spec.args[0][0].equals(Var(_js_expr="ref"))
  214. assert spec.args[0][1].equals(LiteralVar.create("ref_input1"))
  215. assert format.format_event(spec) == 'Event("_set_focus", {ref:"ref_input1"})'
  216. spec = event.set_focus("input1")
  217. assert format.format_event(spec) == 'Event("_set_focus", {ref:"ref_input1"})'
  218. def test_set_value():
  219. """Test the event window alert function."""
  220. spec = event.set_value("input1", "")
  221. assert isinstance(spec, EventSpec)
  222. assert spec.handler.fn.__qualname__ == "_set_value"
  223. assert spec.args[0][0].equals(Var(_js_expr="ref"))
  224. assert spec.args[0][1].equals(LiteralVar.create("ref_input1"))
  225. assert spec.args[1][0].equals(Var(_js_expr="value"))
  226. assert spec.args[1][1].equals(LiteralVar.create(""))
  227. assert (
  228. format.format_event(spec) == 'Event("_set_value", {ref:"ref_input1",value:""})'
  229. )
  230. spec = event.set_value("input1", Var(_js_expr="message"))
  231. assert (
  232. format.format_event(spec)
  233. == 'Event("_set_value", {ref:"ref_input1",value:message})'
  234. )
  235. def test_remove_cookie():
  236. """Test the event remove_cookie."""
  237. spec = event.remove_cookie("testkey")
  238. assert isinstance(spec, EventSpec)
  239. assert spec.handler.fn.__qualname__ == "_remove_cookie"
  240. assert spec.args[0][0].equals(Var(_js_expr="key"))
  241. assert spec.args[0][1].equals(LiteralVar.create("testkey"))
  242. assert spec.args[1][0].equals(Var(_js_expr="options"))
  243. assert spec.args[1][1].equals(LiteralVar.create({"path": "/"}))
  244. assert (
  245. format.format_event(spec)
  246. == 'Event("_remove_cookie", {key:"testkey",options:({ ["path"] : "/" })})'
  247. )
  248. def test_remove_cookie_with_options():
  249. """Test the event remove_cookie with options."""
  250. options = {
  251. "path": "/foo",
  252. "domain": "example.com",
  253. "secure": True,
  254. "sameSite": "strict",
  255. }
  256. spec = event.remove_cookie("testkey", options)
  257. assert isinstance(spec, EventSpec)
  258. assert spec.handler.fn.__qualname__ == "_remove_cookie"
  259. assert spec.args[0][0].equals(Var(_js_expr="key"))
  260. assert spec.args[0][1].equals(LiteralVar.create("testkey"))
  261. assert spec.args[1][0].equals(Var(_js_expr="options"))
  262. assert spec.args[1][1].equals(LiteralVar.create(options))
  263. assert (
  264. format.format_event(spec)
  265. == f'Event("_remove_cookie", {{key:"testkey",options:{str(LiteralVar.create(options))}}})'
  266. )
  267. def test_clear_local_storage():
  268. """Test the event clear_local_storage."""
  269. spec = event.clear_local_storage()
  270. assert isinstance(spec, EventSpec)
  271. assert spec.handler.fn.__qualname__ == "_clear_local_storage"
  272. assert not spec.args
  273. assert format.format_event(spec) == 'Event("_clear_local_storage", {})'
  274. def test_remove_local_storage():
  275. """Test the event remove_local_storage."""
  276. spec = event.remove_local_storage("testkey")
  277. assert isinstance(spec, EventSpec)
  278. assert spec.handler.fn.__qualname__ == "_remove_local_storage"
  279. assert spec.args[0][0].equals(Var(_js_expr="key"))
  280. assert spec.args[0][1].equals(LiteralVar.create("testkey"))
  281. assert (
  282. format.format_event(spec) == 'Event("_remove_local_storage", {key:"testkey"})'
  283. )
  284. def test_event_actions():
  285. """Test DOM event actions, like stopPropagation and preventDefault."""
  286. # EventHandler
  287. handler = EventHandler(fn=lambda: None)
  288. assert not handler.event_actions
  289. sp_handler = handler.stop_propagation
  290. assert handler is not sp_handler
  291. assert sp_handler.event_actions == {"stopPropagation": True}
  292. pd_handler = handler.prevent_default
  293. assert handler is not pd_handler
  294. assert pd_handler.event_actions == {"preventDefault": True}
  295. both_handler = sp_handler.prevent_default
  296. assert both_handler is not sp_handler
  297. assert both_handler.event_actions == {
  298. "stopPropagation": True,
  299. "preventDefault": True,
  300. }
  301. throttle_handler = handler.throttle(300)
  302. assert handler is not throttle_handler
  303. assert throttle_handler.event_actions == {"throttle": 300}
  304. debounce_handler = handler.debounce(300)
  305. assert handler is not debounce_handler
  306. assert debounce_handler.event_actions == {"debounce": 300}
  307. all_handler = handler.stop_propagation.prevent_default.throttle(200).debounce(100)
  308. assert handler is not all_handler
  309. assert all_handler.event_actions == {
  310. "stopPropagation": True,
  311. "preventDefault": True,
  312. "throttle": 200,
  313. "debounce": 100,
  314. }
  315. assert not handler.event_actions
  316. # Convert to EventSpec should carry event actions
  317. sp_handler2 = handler.stop_propagation.throttle(200)
  318. spec = sp_handler2()
  319. assert spec.event_actions == {"stopPropagation": True, "throttle": 200}
  320. assert spec.event_actions == sp_handler2.event_actions
  321. assert spec.event_actions is not sp_handler2.event_actions
  322. # But it should be a copy!
  323. assert spec.event_actions is not sp_handler2.event_actions
  324. spec2 = spec.prevent_default
  325. assert spec is not spec2
  326. assert spec2.event_actions == {
  327. "stopPropagation": True,
  328. "preventDefault": True,
  329. "throttle": 200,
  330. }
  331. assert spec2.event_actions != spec.event_actions
  332. # The original handler should still not be touched.
  333. assert not handler.event_actions
  334. def test_event_actions_on_state():
  335. class EventActionState(BaseState):
  336. def handler(self):
  337. pass
  338. handler = EventActionState.handler
  339. assert isinstance(handler, EventHandler)
  340. assert not handler.event_actions
  341. sp_handler = EventActionState.handler.stop_propagation
  342. assert sp_handler.event_actions == {"stopPropagation": True}
  343. # should NOT affect other references to the handler
  344. assert not handler.event_actions
  345. def test_event_var_data():
  346. class S(BaseState):
  347. x: Field[int] = field(0)
  348. @event
  349. def s(self, value: int):
  350. pass
  351. # Handler doesn't have any _var_data because it's just a str
  352. handler_var = Var.create(S.s)
  353. assert handler_var._get_all_var_data() is None
  354. # Ensure spec carries _var_data
  355. spec_var = Var.create(S.s(S.x))
  356. assert spec_var._get_all_var_data() == S.x._get_all_var_data()
  357. # Needed to instantiate the EventChain
  358. def _args_spec(value: Var[int]) -> tuple[Var[int]]:
  359. return (value,)
  360. # Ensure chain carries _var_data
  361. chain_var = Var.create(EventChain(events=[S.s(S.x)], args_spec=_args_spec))
  362. assert chain_var._get_all_var_data() == S.x._get_all_var_data()