test_state.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366
  1. from __future__ import annotations
  2. import datetime
  3. import functools
  4. from typing import Dict, List
  5. import pytest
  6. from plotly.graph_objects import Figure
  7. import reflex as rx
  8. from reflex.base import Base
  9. from reflex.constants import IS_HYDRATED, RouteVar
  10. from reflex.event import Event, EventHandler
  11. from reflex.state import State
  12. from reflex.utils import format
  13. from reflex.vars import BaseVar, ComputedVar, ReflexDict, ReflexList, ReflexSet
  14. class Object(Base):
  15. """A test object fixture."""
  16. prop1: int = 42
  17. prop2: str = "hello"
  18. class TestState(State):
  19. """A test state."""
  20. # Set this class as not test one
  21. __test__ = False
  22. num1: int
  23. num2: float = 3.14
  24. key: str
  25. map_key: str = "a"
  26. array: List[float] = [1, 2, 3.14]
  27. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  28. obj: Object = Object()
  29. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  30. fig: Figure = Figure()
  31. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  32. @ComputedVar
  33. def sum(self) -> float:
  34. """Dynamically sum the numbers.
  35. Returns:
  36. The sum of the numbers.
  37. """
  38. return self.num1 + self.num2
  39. @ComputedVar
  40. def upper(self) -> str:
  41. """Uppercase the key.
  42. Returns:
  43. The uppercased key.
  44. """
  45. return self.key.upper()
  46. def do_something(self):
  47. """Do something."""
  48. pass
  49. class ChildState(TestState):
  50. """A child state fixture."""
  51. value: str
  52. count: int = 23
  53. def change_both(self, value: str, count: int):
  54. """Change both the value and count.
  55. Args:
  56. value: The new value.
  57. count: The new count.
  58. """
  59. self.value = value.upper()
  60. self.count = count * 2
  61. class ChildState2(TestState):
  62. """A child state fixture."""
  63. value: str
  64. class GrandchildState(ChildState):
  65. """A grandchild state fixture."""
  66. value2: str
  67. def do_nothing(self):
  68. """Do something."""
  69. pass
  70. @pytest.fixture
  71. def test_state() -> TestState:
  72. """A state.
  73. Returns:
  74. A test state.
  75. """
  76. return TestState() # type: ignore
  77. @pytest.fixture
  78. def child_state(test_state) -> ChildState:
  79. """A child state.
  80. Args:
  81. test_state: A test state.
  82. Returns:
  83. A test child state.
  84. """
  85. child_state = test_state.get_substate(["child_state"])
  86. assert child_state is not None
  87. return child_state
  88. @pytest.fixture
  89. def child_state2(test_state) -> ChildState2:
  90. """A second child state.
  91. Args:
  92. test_state: A test state.
  93. Returns:
  94. A second test child state.
  95. """
  96. child_state2 = test_state.get_substate(["child_state2"])
  97. assert child_state2 is not None
  98. return child_state2
  99. @pytest.fixture
  100. def grandchild_state(child_state) -> GrandchildState:
  101. """A state.
  102. Args:
  103. child_state: A child state.
  104. Returns:
  105. A test state.
  106. """
  107. grandchild_state = child_state.get_substate(["grandchild_state"])
  108. assert grandchild_state is not None
  109. return grandchild_state
  110. def test_base_class_vars(test_state):
  111. """Test that the class vars are set correctly.
  112. Args:
  113. test_state: A state.
  114. """
  115. fields = test_state.get_fields()
  116. cls = type(test_state)
  117. for field in fields:
  118. if field in test_state.get_skip_vars():
  119. continue
  120. prop = getattr(cls, field)
  121. assert isinstance(prop, BaseVar)
  122. assert prop.name == field
  123. assert cls.num1.type_ == int
  124. assert cls.num2.type_ == float
  125. assert cls.key.type_ == str
  126. def test_computed_class_var(test_state):
  127. """Test that the class computed vars are set correctly.
  128. Args:
  129. test_state: A state.
  130. """
  131. cls = type(test_state)
  132. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  133. assert ("sum", float) in vars
  134. assert ("upper", str) in vars
  135. def test_class_vars(test_state):
  136. """Test that the class vars are set correctly.
  137. Args:
  138. test_state: A state.
  139. """
  140. cls = type(test_state)
  141. assert set(cls.vars.keys()) == {
  142. IS_HYDRATED, # added by hydrate_middleware to all State
  143. "num1",
  144. "num2",
  145. "key",
  146. "map_key",
  147. "array",
  148. "mapping",
  149. "obj",
  150. "complex",
  151. "sum",
  152. "upper",
  153. "fig",
  154. "dt",
  155. }
  156. def test_event_handlers(test_state):
  157. """Test that event handler is set correctly.
  158. Args:
  159. test_state: A state.
  160. """
  161. expected = {
  162. "do_something",
  163. "set_array",
  164. "set_complex",
  165. "set_fig",
  166. "set_key",
  167. "set_mapping",
  168. "set_num1",
  169. "set_num2",
  170. "set_obj",
  171. }
  172. cls = type(test_state)
  173. assert set(cls.event_handlers.keys()).intersection(expected) == expected
  174. def test_default_value(test_state):
  175. """Test that the default value of a var is correct.
  176. Args:
  177. test_state: A state.
  178. """
  179. assert test_state.num1 == 0
  180. assert test_state.num2 == 3.14
  181. assert test_state.key == ""
  182. assert test_state.sum == 3.14
  183. assert test_state.upper == ""
  184. def test_computed_vars(test_state):
  185. """Test that the computed var is computed correctly.
  186. Args:
  187. test_state: A state.
  188. """
  189. test_state.num1 = 1
  190. test_state.num2 = 4
  191. assert test_state.sum == 5
  192. test_state.key = "hello world"
  193. assert test_state.upper == "HELLO WORLD"
  194. def test_dict(test_state):
  195. """Test that the dict representation of a state is correct.
  196. Args:
  197. test_state: A state.
  198. """
  199. substates = {"child_state", "child_state2"}
  200. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  201. assert (
  202. set(test_state.dict(include_computed=False).keys())
  203. == set(test_state.base_vars) | substates
  204. )
  205. def test_format_state(test_state):
  206. """Test that the format state is correct.
  207. Args:
  208. test_state: A state.
  209. """
  210. formatted_state = format.format_state(test_state.dict())
  211. exp_formatted_state = {
  212. "array": [1, 2, 3.14],
  213. "child_state": {"count": 23, "grandchild_state": {"value2": ""}, "value": ""},
  214. "child_state2": {"value": ""},
  215. "complex": {
  216. 1: {"prop1": 42, "prop2": "hello"},
  217. 2: {"prop1": 42, "prop2": "hello"},
  218. },
  219. "dt": "1989-11-09 18:53:00+01:00",
  220. "fig": [],
  221. "is_hydrated": False,
  222. "key": "",
  223. "map_key": "a",
  224. "mapping": {"a": [1, 2, 3], "b": [4, 5, 6]},
  225. "num1": 0,
  226. "num2": 3.14,
  227. "obj": {"prop1": 42, "prop2": "hello"},
  228. "sum": 3.14,
  229. "upper": "",
  230. }
  231. assert formatted_state == exp_formatted_state
  232. def test_format_state_datetime():
  233. """Test that the format state is correct for datetime classes."""
  234. class DateTimeState(State):
  235. d: datetime.date = datetime.date.fromisoformat("1989-11-09")
  236. dt: datetime.datetime = datetime.datetime.fromisoformat(
  237. "1989-11-09T18:53:00+01:00"
  238. )
  239. t: datetime.time = datetime.time.fromisoformat("18:53:00+01:00")
  240. td: datetime.timedelta = datetime.timedelta(days=11, minutes=11)
  241. formatted_state = format.format_state(DateTimeState().dict())
  242. exp_formatted_state = {
  243. "d": "1989-11-09",
  244. "dt": "1989-11-09 18:53:00+01:00",
  245. "is_hydrated": False,
  246. "t": "18:53:00+01:00",
  247. "td": "11 days, 0:11:00",
  248. }
  249. assert formatted_state == exp_formatted_state
  250. def test_default_setters(test_state):
  251. """Test that we can set default values.
  252. Args:
  253. test_state: A state.
  254. """
  255. for prop_name in test_state.base_vars:
  256. # Each base var should have a default setter.
  257. assert hasattr(test_state, f"set_{prop_name}")
  258. def test_class_indexing_with_vars():
  259. """Test that we can index into a state var with another var."""
  260. prop = TestState.array[TestState.num1]
  261. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  262. prop = TestState.mapping["a"][TestState.num1]
  263. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  264. prop = TestState.mapping[TestState.map_key]
  265. assert str(prop) == "{test_state.mapping[test_state.map_key]}"
  266. def test_class_attributes():
  267. """Test that we can get class attributes."""
  268. prop = TestState.obj.prop1
  269. assert str(prop) == "{test_state.obj.prop1}"
  270. prop = TestState.complex[1].prop1
  271. assert str(prop) == "{test_state.complex[1].prop1}"
  272. def test_get_parent_state():
  273. """Test getting the parent state."""
  274. assert TestState.get_parent_state() is None
  275. assert ChildState.get_parent_state() == TestState
  276. assert ChildState2.get_parent_state() == TestState
  277. assert GrandchildState.get_parent_state() == ChildState
  278. def test_get_substates():
  279. """Test getting the substates."""
  280. assert TestState.get_substates() == {ChildState, ChildState2}
  281. assert ChildState.get_substates() == {GrandchildState}
  282. assert ChildState2.get_substates() == set()
  283. assert GrandchildState.get_substates() == set()
  284. def test_get_name():
  285. """Test getting the name of a state."""
  286. assert TestState.get_name() == "test_state"
  287. assert ChildState.get_name() == "child_state"
  288. assert ChildState2.get_name() == "child_state2"
  289. assert GrandchildState.get_name() == "grandchild_state"
  290. def test_get_full_name():
  291. """Test getting the full name."""
  292. assert TestState.get_full_name() == "test_state"
  293. assert ChildState.get_full_name() == "test_state.child_state"
  294. assert ChildState2.get_full_name() == "test_state.child_state2"
  295. assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
  296. def test_get_class_substate():
  297. """Test getting the substate of a class."""
  298. assert TestState.get_class_substate(("child_state",)) == ChildState
  299. assert TestState.get_class_substate(("child_state2",)) == ChildState2
  300. assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
  301. assert (
  302. TestState.get_class_substate(("child_state", "grandchild_state"))
  303. == GrandchildState
  304. )
  305. with pytest.raises(ValueError):
  306. TestState.get_class_substate(("invalid_child",))
  307. with pytest.raises(ValueError):
  308. TestState.get_class_substate(
  309. (
  310. "child_state",
  311. "invalid_child",
  312. )
  313. )
  314. def test_get_class_var():
  315. """Test getting the var of a class."""
  316. assert TestState.get_class_var(("num1",)) == TestState.num1
  317. assert TestState.get_class_var(("num2",)) == TestState.num2
  318. assert ChildState.get_class_var(("value",)) == ChildState.value
  319. assert GrandchildState.get_class_var(("value2",)) == GrandchildState.value2
  320. assert TestState.get_class_var(("child_state", "value")) == ChildState.value
  321. assert (
  322. TestState.get_class_var(("child_state", "grandchild_state", "value2"))
  323. == GrandchildState.value2
  324. )
  325. assert (
  326. ChildState.get_class_var(("grandchild_state", "value2"))
  327. == GrandchildState.value2
  328. )
  329. with pytest.raises(ValueError):
  330. TestState.get_class_var(("invalid_var",))
  331. with pytest.raises(ValueError):
  332. TestState.get_class_var(
  333. (
  334. "child_state",
  335. "invalid_var",
  336. )
  337. )
  338. def test_set_class_var():
  339. """Test setting the var of a class."""
  340. with pytest.raises(AttributeError):
  341. TestState.num3 # type: ignore
  342. TestState._set_var(BaseVar(name="num3", type_=int).set_state(TestState))
  343. var = TestState.num3 # type: ignore
  344. assert var.name == "num3"
  345. assert var.type_ == int
  346. assert var.state == TestState.get_full_name()
  347. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  348. """Test setting the parent and substates.
  349. Args:
  350. test_state: A state.
  351. child_state: A child state.
  352. grandchild_state: A grandchild state.
  353. """
  354. assert len(test_state.substates) == 2
  355. assert set(test_state.substates) == {"child_state", "child_state2"}
  356. assert child_state.parent_state == test_state
  357. assert len(child_state.substates) == 1
  358. assert set(child_state.substates) == {"grandchild_state"}
  359. assert grandchild_state.parent_state == child_state
  360. assert len(grandchild_state.substates) == 0
  361. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  362. """Test getting the attribute of a state.
  363. Args:
  364. test_state: A state.
  365. child_state: A child state.
  366. child_state2: A child state.
  367. grandchild_state: A grandchild state.
  368. """
  369. assert test_state.num1 == 0
  370. assert child_state.value == ""
  371. assert child_state2.value == ""
  372. assert child_state.count == 23
  373. assert grandchild_state.value2 == ""
  374. with pytest.raises(AttributeError):
  375. test_state.invalid
  376. with pytest.raises(AttributeError):
  377. test_state.child_state.invalid
  378. with pytest.raises(AttributeError):
  379. test_state.child_state.grandchild_state.invalid
  380. def test_set_child_attribute(test_state, child_state, grandchild_state):
  381. """Test setting the attribute of a state.
  382. Args:
  383. test_state: A state.
  384. child_state: A child state.
  385. grandchild_state: A grandchild state.
  386. """
  387. test_state.num1 = 10
  388. assert test_state.num1 == 10
  389. assert child_state.num1 == 10
  390. assert grandchild_state.num1 == 10
  391. grandchild_state.num1 = 5
  392. assert test_state.num1 == 5
  393. assert child_state.num1 == 5
  394. assert grandchild_state.num1 == 5
  395. child_state.value = "test"
  396. assert child_state.value == "test"
  397. assert grandchild_state.value == "test"
  398. grandchild_state.value = "test2"
  399. assert child_state.value == "test2"
  400. assert grandchild_state.value == "test2"
  401. grandchild_state.value2 = "test3"
  402. assert grandchild_state.value2 == "test3"
  403. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  404. """Test getting the substate of a state.
  405. Args:
  406. test_state: A state.
  407. child_state: A child state.
  408. child_state2: A child state.
  409. grandchild_state: A grandchild state.
  410. """
  411. assert test_state.get_substate(("child_state",)) == child_state
  412. assert test_state.get_substate(("child_state2",)) == child_state2
  413. assert (
  414. test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
  415. )
  416. assert child_state.get_substate(("grandchild_state",)) == grandchild_state
  417. with pytest.raises(ValueError):
  418. test_state.get_substate(("invalid",))
  419. with pytest.raises(ValueError):
  420. test_state.get_substate(("child_state", "invalid"))
  421. with pytest.raises(ValueError):
  422. test_state.get_substate(("child_state", "grandchild_state", "invalid"))
  423. def test_set_dirty_var(test_state):
  424. """Test changing state vars marks the value as dirty.
  425. Args:
  426. test_state: A state.
  427. """
  428. # Initially there should be no dirty vars.
  429. assert test_state.dirty_vars == set()
  430. # Setting a var should mark it as dirty.
  431. test_state.num1 = 1
  432. assert test_state.dirty_vars == {"num1", "sum"}
  433. # Setting another var should mark it as dirty.
  434. test_state.num2 = 2
  435. assert test_state.dirty_vars == {"num1", "num2", "sum"}
  436. # Cleaning the state should remove all dirty vars.
  437. test_state._clean()
  438. assert test_state.dirty_vars == set()
  439. def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
  440. """Test changing substate vars marks the value as dirty.
  441. Args:
  442. test_state: A state.
  443. child_state: A child state.
  444. child_state2: A child state.
  445. grandchild_state: A grandchild state.
  446. """
  447. # Initially there should be no dirty vars.
  448. assert test_state.dirty_vars == set()
  449. assert child_state.dirty_vars == set()
  450. assert child_state2.dirty_vars == set()
  451. assert grandchild_state.dirty_vars == set()
  452. # Setting a var should mark it as dirty.
  453. child_state.value = "test"
  454. assert child_state.dirty_vars == {"value"}
  455. assert test_state.dirty_substates == {"child_state"}
  456. assert child_state.dirty_substates == set()
  457. # Cleaning the parent state should remove the dirty substate.
  458. test_state._clean()
  459. assert test_state.dirty_substates == set()
  460. assert child_state.dirty_vars == set()
  461. # Setting a var on the grandchild should bubble up.
  462. grandchild_state.value2 = "test2"
  463. assert child_state.dirty_substates == {"grandchild_state"}
  464. assert test_state.dirty_substates == {"child_state"}
  465. # Cleaning the middle state should keep the parent state dirty.
  466. child_state._clean()
  467. assert test_state.dirty_substates == {"child_state"}
  468. assert child_state.dirty_substates == set()
  469. assert grandchild_state.dirty_vars == set()
  470. def test_reset(test_state, child_state):
  471. """Test resetting the state.
  472. Args:
  473. test_state: A state.
  474. child_state: A child state.
  475. """
  476. # Set some values.
  477. test_state.num1 = 1
  478. test_state.num2 = 2
  479. child_state.value = "test"
  480. # Reset the state.
  481. test_state.reset()
  482. # The values should be reset.
  483. assert test_state.num1 == 0
  484. assert test_state.num2 == 3.14
  485. assert child_state.value == ""
  486. expected_dirty_vars = {
  487. "num1",
  488. "num2",
  489. "obj",
  490. "upper",
  491. "complex",
  492. "is_hydrated",
  493. "fig",
  494. "key",
  495. "sum",
  496. "array",
  497. "map_key",
  498. "mapping",
  499. "dt",
  500. }
  501. # The dirty vars should be reset.
  502. assert test_state.dirty_vars == expected_dirty_vars
  503. assert child_state.dirty_vars == {"count", "value"}
  504. # The dirty substates should be reset.
  505. assert test_state.dirty_substates == {"child_state", "child_state2"}
  506. @pytest.mark.asyncio
  507. async def test_process_event_simple(test_state):
  508. """Test processing an event.
  509. Args:
  510. test_state: A state.
  511. """
  512. assert test_state.num1 == 0
  513. event = Event(token="t", name="set_num1", payload={"value": 69})
  514. update = await test_state._process(event).__anext__()
  515. # The event should update the value.
  516. assert test_state.num1 == 69
  517. # The delta should contain the changes, including computed vars.
  518. # assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  519. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14, "upper": ""}}
  520. assert update.events == []
  521. @pytest.mark.asyncio
  522. async def test_process_event_substate(test_state, child_state, grandchild_state):
  523. """Test processing an event on a substate.
  524. Args:
  525. test_state: A state.
  526. child_state: A child state.
  527. grandchild_state: A grandchild state.
  528. """
  529. # Events should bubble down to the substate.
  530. assert child_state.value == ""
  531. assert child_state.count == 23
  532. event = Event(
  533. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  534. )
  535. update = await test_state._process(event).__anext__()
  536. assert child_state.value == "HI"
  537. assert child_state.count == 24
  538. assert update.delta == {
  539. "test_state": {"sum": 3.14, "upper": ""},
  540. "test_state.child_state": {"value": "HI", "count": 24},
  541. }
  542. test_state._clean()
  543. # Test with the granchild state.
  544. assert grandchild_state.value2 == ""
  545. event = Event(
  546. token="t",
  547. name="child_state.grandchild_state.set_value2",
  548. payload={"value": "new"},
  549. )
  550. update = await test_state._process(event).__anext__()
  551. assert grandchild_state.value2 == "new"
  552. assert update.delta == {
  553. "test_state": {"sum": 3.14, "upper": ""},
  554. "test_state.child_state.grandchild_state": {"value2": "new"},
  555. }
  556. @pytest.mark.asyncio
  557. async def test_process_event_generator(gen_state):
  558. """Test event handlers that generate multiple updates.
  559. Args:
  560. gen_state: A state.
  561. """
  562. gen_state = gen_state()
  563. event = Event(
  564. token="t",
  565. name="go",
  566. payload={"c": 5},
  567. )
  568. gen = gen_state._process(event)
  569. count = 0
  570. async for update in gen:
  571. count += 1
  572. if count == 6:
  573. assert update.delta == {}
  574. assert update.final
  575. else:
  576. assert gen_state.value == count
  577. assert update.delta == {
  578. "gen_state": {"value": count},
  579. }
  580. assert not update.final
  581. assert count == 6
  582. def test_format_event_handler():
  583. """Test formatting an event handler."""
  584. assert (
  585. format.format_event_handler(TestState.do_something) == "test_state.do_something" # type: ignore
  586. )
  587. assert (
  588. format.format_event_handler(ChildState.change_both) # type: ignore
  589. == "test_state.child_state.change_both"
  590. )
  591. assert (
  592. format.format_event_handler(GrandchildState.do_nothing) # type: ignore
  593. == "test_state.child_state.grandchild_state.do_nothing"
  594. )
  595. def test_get_token(test_state, mocker, router_data):
  596. """Test that the token obtained from the router_data is correct.
  597. Args:
  598. test_state: The test state.
  599. mocker: Pytest Mocker object.
  600. router_data: The router data fixture.
  601. """
  602. mocker.patch.object(test_state, "router_data", router_data)
  603. assert test_state.get_token() == "b181904c-3953-4a79-dc18-ae9518c22f05"
  604. def test_get_sid(test_state, mocker, router_data):
  605. """Test getting session id.
  606. Args:
  607. test_state: A state.
  608. mocker: Pytest Mocker object.
  609. router_data: The router data fixture.
  610. """
  611. mocker.patch.object(test_state, "router_data", router_data)
  612. assert test_state.get_sid() == "9fpxSzPb9aFMb4wFAAAH"
  613. def test_get_headers(test_state, mocker, router_data, router_data_headers):
  614. """Test getting client headers.
  615. Args:
  616. test_state: A state.
  617. mocker: Pytest Mocker object.
  618. router_data: The router data fixture.
  619. router_data_headers: The expected headers.
  620. """
  621. mocker.patch.object(test_state, "router_data", router_data)
  622. assert test_state.get_headers() == router_data_headers
  623. def test_get_client_ip(test_state, mocker, router_data):
  624. """Test getting client IP.
  625. Args:
  626. test_state: A state.
  627. mocker: Pytest Mocker object.
  628. router_data: The router data fixture.
  629. """
  630. mocker.patch.object(test_state, "router_data", router_data)
  631. assert test_state.get_client_ip() == "127.0.0.1"
  632. def test_get_cookies(test_state, mocker, router_data):
  633. """Test getting client cookies.
  634. Args:
  635. test_state: A state.
  636. mocker: Pytest Mocker object.
  637. router_data: The router data fixture.
  638. """
  639. mocker.patch.object(test_state, "router_data", router_data)
  640. assert test_state.get_cookies() == {
  641. "csrftoken": "mocktoken",
  642. "name": "reflex",
  643. "list_cookies": ["some", "random", "cookies"],
  644. "dict_cookies": {"name": "reflex"},
  645. "val": True,
  646. }
  647. def test_get_current_page(test_state):
  648. assert test_state.get_current_page() == ""
  649. route = "mypage/subpage"
  650. test_state.router_data = {RouteVar.PATH: route}
  651. assert test_state.get_current_page() == route
  652. def test_get_query_params(test_state):
  653. assert test_state.get_query_params() == {}
  654. params = {"p1": "a", "p2": "b"}
  655. test_state.router_data = {RouteVar.QUERY: params}
  656. assert test_state.get_query_params() == params
  657. def test_add_var(test_state):
  658. test_state.add_var("dynamic_int", int, 42)
  659. assert test_state.dynamic_int == 42
  660. test_state.add_var("dynamic_list", List[int], [5, 10])
  661. assert test_state.dynamic_list == [5, 10]
  662. assert test_state.dynamic_list == [5, 10]
  663. # how to test that one?
  664. # test_state.dynamic_list.append(15)
  665. # assert test_state.dynamic_list == [5, 10, 15]
  666. test_state.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  667. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  668. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  669. def test_add_var_default_handlers(test_state):
  670. test_state.add_var("rand_int", int, 10)
  671. assert "set_rand_int" in test_state.event_handlers
  672. assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
  673. class InterdependentState(State):
  674. """A state with 3 vars and 3 computed vars.
  675. x: a variable that no computed var depends on
  676. v1: a varable that one computed var directly depeneds on
  677. _v2: a backend variable that one computed var directly depends on
  678. v1x2: a computed var that depends on v1
  679. v2x2: a computed var that depends on backend var _v2
  680. v1x2x2: a computed var that depends on computed var v1x2
  681. """
  682. x: int = 0
  683. v1: int = 0
  684. _v2: int = 1
  685. @rx.cached_var
  686. def v1x2(self) -> int:
  687. """Depends on var v1.
  688. Returns:
  689. Var v1 multiplied by 2
  690. """
  691. return self.v1 * 2
  692. @rx.cached_var
  693. def v2x2(self) -> int:
  694. """Depends on backend var _v2.
  695. Returns:
  696. backend var _v2 multiplied by 2
  697. """
  698. return self._v2 * 2
  699. @rx.cached_var
  700. def v1x2x2(self) -> int:
  701. """Depends on ComputedVar v1x2.
  702. Returns:
  703. ComputedVar v1x2 multiplied by 2
  704. """
  705. return self.v1x2 * 2
  706. @pytest.fixture
  707. def interdependent_state() -> State:
  708. """A state with varying dependency between vars.
  709. Returns:
  710. instance of InterdependentState
  711. """
  712. s = InterdependentState()
  713. s.dict() # prime initial relationships by accessing all ComputedVars
  714. return s
  715. def test_not_dirty_computed_var_from_var(interdependent_state):
  716. """Set Var that no ComputedVar depends on, expect no recalculation.
  717. Args:
  718. interdependent_state: A state with varying Var dependencies.
  719. """
  720. interdependent_state.x = 5
  721. assert interdependent_state.get_delta() == {
  722. interdependent_state.get_full_name(): {"x": 5},
  723. }
  724. def test_dirty_computed_var_from_var(interdependent_state):
  725. """Set Var that ComputedVar depends on, expect recalculation.
  726. The other ComputedVar depends on the changed ComputedVar and should also be
  727. recalculated. No other ComputedVars should be recalculated.
  728. Args:
  729. interdependent_state: A state with varying Var dependencies.
  730. """
  731. interdependent_state.v1 = 1
  732. assert interdependent_state.get_delta() == {
  733. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  734. }
  735. def test_dirty_computed_var_from_backend_var(interdependent_state):
  736. """Set backend var that ComputedVar depends on, expect recalculation.
  737. Args:
  738. interdependent_state: A state with varying Var dependencies.
  739. """
  740. interdependent_state._v2 = 2
  741. assert interdependent_state.get_delta() == {
  742. interdependent_state.get_full_name(): {"v2x2": 4},
  743. }
  744. def test_per_state_backend_var(interdependent_state):
  745. """Set backend var on one instance, expect no affect in other instances.
  746. Args:
  747. interdependent_state: A state with varying Var dependencies.
  748. """
  749. s2 = InterdependentState()
  750. assert s2._v2 == interdependent_state._v2
  751. interdependent_state._v2 = 2
  752. assert s2._v2 != interdependent_state._v2
  753. s3 = InterdependentState()
  754. assert s3._v2 != interdependent_state._v2
  755. # both s2 and s3 should still have the default value
  756. assert s2._v2 == s3._v2
  757. # changing s2._v2 should not affect others
  758. s2._v2 = 4
  759. assert s2._v2 != interdependent_state._v2
  760. assert s2._v2 != s3._v2
  761. def test_child_state():
  762. """Test that the child state computed vars can reference parent state vars."""
  763. class MainState(State):
  764. v: int = 2
  765. class ChildState(MainState):
  766. @ComputedVar
  767. def rendered_var(self):
  768. return self.v
  769. ms = MainState()
  770. cs = ms.substates[ChildState.get_name()]
  771. assert ms.v == 2
  772. assert cs.v == 2
  773. assert cs.rendered_var == 2
  774. def test_conditional_computed_vars():
  775. """Test that computed vars can have conditionals."""
  776. class MainState(State):
  777. flag: bool = False
  778. t1: str = "a"
  779. t2: str = "b"
  780. @ComputedVar
  781. def rendered_var(self) -> str:
  782. if self.flag:
  783. return self.t1
  784. return self.t2
  785. ms = MainState()
  786. # Initially there are no dirty computed vars.
  787. assert ms._dirty_computed_vars(from_vars={"flag"}) == {"rendered_var"}
  788. assert ms._dirty_computed_vars(from_vars={"t2"}) == {"rendered_var"}
  789. assert ms._dirty_computed_vars(from_vars={"t1"}) == {"rendered_var"}
  790. assert ms.computed_vars["rendered_var"].deps(objclass=MainState) == {
  791. "flag",
  792. "t1",
  793. "t2",
  794. }
  795. def test_event_handlers_convert_to_fns(test_state, child_state):
  796. """Test that when the state is initialized, event handlers are converted to fns.
  797. Args:
  798. test_state: A state with event handlers.
  799. child_state: A child state with event handlers.
  800. """
  801. # The class instances should be event handlers.
  802. assert isinstance(TestState.do_something, EventHandler)
  803. assert isinstance(ChildState.change_both, EventHandler)
  804. # The object instances should be fns.
  805. test_state.do_something()
  806. child_state.change_both(value="goose", count=9)
  807. assert child_state.value == "GOOSE"
  808. assert child_state.count == 18
  809. def test_event_handlers_call_other_handlers():
  810. """Test that event handlers can call other event handlers."""
  811. class MainState(State):
  812. v: int = 0
  813. def set_v(self, v: int):
  814. self.v = v
  815. def set_v2(self, v: int):
  816. self.set_v(v)
  817. class SubState(MainState):
  818. def set_v3(self, v: int):
  819. self.set_v2(v)
  820. ms = MainState()
  821. ms.set_v2(1)
  822. assert ms.v == 1
  823. # ensure handler can be called from substate
  824. ms.substates[SubState.get_name()].set_v3(2)
  825. assert ms.v == 2
  826. def test_computed_var_cached():
  827. """Test that a ComputedVar doesn't recalculate when accessed."""
  828. comp_v_calls = 0
  829. class ComputedState(State):
  830. v: int = 0
  831. @rx.cached_var
  832. def comp_v(self) -> int:
  833. nonlocal comp_v_calls
  834. comp_v_calls += 1
  835. return self.v
  836. cs = ComputedState()
  837. assert cs.dict()["v"] == 0
  838. assert comp_v_calls == 1
  839. assert cs.dict()["comp_v"] == 0
  840. assert comp_v_calls == 1
  841. assert cs.comp_v == 0
  842. assert comp_v_calls == 1
  843. cs.v = 1
  844. assert comp_v_calls == 1
  845. assert cs.comp_v == 1
  846. assert comp_v_calls == 2
  847. def test_computed_var_cached_depends_on_non_cached():
  848. """Test that a cached_var is recalculated if it depends on non-cached ComputedVar."""
  849. class ComputedState(State):
  850. v: int = 0
  851. @rx.var
  852. def no_cache_v(self) -> int:
  853. return self.v
  854. @rx.cached_var
  855. def dep_v(self) -> int:
  856. return self.no_cache_v
  857. @rx.cached_var
  858. def comp_v(self) -> int:
  859. return self.v
  860. cs = ComputedState()
  861. assert cs.dirty_vars == set()
  862. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  863. cs._clean()
  864. assert cs.dirty_vars == set()
  865. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  866. cs._clean()
  867. assert cs.dirty_vars == set()
  868. cs.v = 1
  869. assert cs.dirty_vars == {"v", "comp_v", "dep_v", "no_cache_v"}
  870. assert cs.get_delta() == {
  871. cs.get_name(): {"v": 1, "no_cache_v": 1, "dep_v": 1, "comp_v": 1}
  872. }
  873. cs._clean()
  874. assert cs.dirty_vars == set()
  875. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  876. cs._clean()
  877. assert cs.dirty_vars == set()
  878. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  879. cs._clean()
  880. assert cs.dirty_vars == set()
  881. def test_computed_var_depends_on_parent_non_cached():
  882. """Child state cached_var that depends on parent state un cached var is always recalculated."""
  883. counter = 0
  884. class ParentState(State):
  885. @rx.var
  886. def no_cache_v(self) -> int:
  887. nonlocal counter
  888. counter += 1
  889. return counter
  890. class ChildState(ParentState):
  891. @rx.cached_var
  892. def dep_v(self) -> int:
  893. return self.no_cache_v
  894. ps = ParentState()
  895. cs = ps.substates[ChildState.get_name()]
  896. assert ps.dirty_vars == set()
  897. assert cs.dirty_vars == set()
  898. assert ps.dict() == {
  899. cs.get_name(): {"dep_v": 2},
  900. "no_cache_v": 1,
  901. IS_HYDRATED: False,
  902. }
  903. assert ps.dict() == {
  904. cs.get_name(): {"dep_v": 4},
  905. "no_cache_v": 3,
  906. IS_HYDRATED: False,
  907. }
  908. assert ps.dict() == {
  909. cs.get_name(): {"dep_v": 6},
  910. "no_cache_v": 5,
  911. IS_HYDRATED: False,
  912. }
  913. assert counter == 6
  914. @pytest.mark.parametrize("use_partial", [True, False])
  915. def test_cached_var_depends_on_event_handler(use_partial: bool):
  916. """A cached_var that calls an event handler calculates deps correctly.
  917. Args:
  918. use_partial: if true, replace the EventHandler with functools.partial
  919. """
  920. counter = 0
  921. class HandlerState(State):
  922. x: int = 42
  923. def handler(self):
  924. self.x = self.x + 1
  925. @rx.cached_var
  926. def cached_x_side_effect(self) -> int:
  927. self.handler()
  928. nonlocal counter
  929. counter += 1
  930. return counter
  931. if use_partial:
  932. HandlerState.handler = functools.partial(HandlerState.handler.fn)
  933. assert isinstance(HandlerState.handler, functools.partial)
  934. else:
  935. assert isinstance(HandlerState.handler, EventHandler)
  936. s = HandlerState()
  937. assert "cached_x_side_effect" in s.computed_var_dependencies["x"]
  938. assert s.cached_x_side_effect == 1
  939. assert s.x == 43
  940. s.handler()
  941. assert s.cached_x_side_effect == 2
  942. assert s.x == 45
  943. def test_computed_var_dependencies():
  944. """Test that a ComputedVar correctly tracks its dependencies."""
  945. class ComputedState(State):
  946. v: int = 0
  947. w: int = 0
  948. x: int = 0
  949. y: List[int] = [1, 2, 3]
  950. _z: List[int] = [1, 2, 3]
  951. @rx.cached_var
  952. def comp_v(self) -> int:
  953. """Direct access.
  954. Returns:
  955. The value of self.v.
  956. """
  957. return self.v
  958. @rx.cached_var
  959. def comp_w(self):
  960. """Nested lambda.
  961. Returns:
  962. A lambda that returns the value of self.w.
  963. """
  964. return lambda: self.w
  965. @rx.cached_var
  966. def comp_x(self):
  967. """Nested function.
  968. Returns:
  969. A function that returns the value of self.x.
  970. """
  971. def _():
  972. return self.x
  973. return _
  974. @rx.cached_var
  975. def comp_y(self) -> List[int]:
  976. """Comprehension iterating over attribute.
  977. Returns:
  978. A list of the values of self.y.
  979. """
  980. return [round(y) for y in self.y]
  981. @rx.cached_var
  982. def comp_z(self) -> List[bool]:
  983. """Comprehension accesses attribute.
  984. Returns:
  985. A list of whether the values 0-4 are in self._z.
  986. """
  987. return [z in self._z for z in range(5)]
  988. cs = ComputedState()
  989. assert cs.computed_var_dependencies["v"] == {"comp_v"}
  990. assert cs.computed_var_dependencies["w"] == {"comp_w"}
  991. assert cs.computed_var_dependencies["x"] == {"comp_x"}
  992. assert cs.computed_var_dependencies["y"] == {"comp_y"}
  993. assert cs.computed_var_dependencies["_z"] == {"comp_z"}
  994. def test_backend_method():
  995. """A method with leading underscore should be callable from event handler."""
  996. class BackendMethodState(State):
  997. def _be_method(self):
  998. return True
  999. def handler(self):
  1000. assert self._be_method()
  1001. bms = BackendMethodState()
  1002. bms.handler()
  1003. assert bms._be_method()
  1004. def test_setattr_of_mutable_types(mutable_state):
  1005. """Test that mutable types are converted to corresponding Reflex wrappers.
  1006. Args:
  1007. mutable_state: A test state.
  1008. """
  1009. array = mutable_state.array
  1010. hashmap = mutable_state.hashmap
  1011. test_set = mutable_state.test_set
  1012. assert isinstance(array, ReflexList)
  1013. assert isinstance(array[1], ReflexList)
  1014. assert isinstance(array[2], ReflexDict)
  1015. assert isinstance(hashmap, ReflexDict)
  1016. assert isinstance(hashmap["key"], ReflexList)
  1017. assert isinstance(hashmap["third_key"], ReflexDict)
  1018. assert isinstance(test_set, set)
  1019. mutable_state.reassign_mutables()
  1020. array = mutable_state.array
  1021. hashmap = mutable_state.hashmap
  1022. test_set = mutable_state.test_set
  1023. assert isinstance(array, ReflexList)
  1024. assert isinstance(array[1], ReflexList)
  1025. assert isinstance(array[2], ReflexDict)
  1026. assert isinstance(hashmap, ReflexDict)
  1027. assert isinstance(hashmap["mod_key"], ReflexList)
  1028. assert isinstance(hashmap["mod_third_key"], ReflexDict)
  1029. assert isinstance(test_set, ReflexSet)
  1030. def test_error_on_state_method_shadow():
  1031. """Test that an error is thrown when an event handler shadows a state method."""
  1032. with pytest.raises(NameError) as err:
  1033. class InvalidTest(rx.State):
  1034. def reset(self):
  1035. pass
  1036. assert (
  1037. err.value.args[0]
  1038. == f"The event handler name `reset` shadows a builtin State method; use a different name instead"
  1039. )
  1040. def test_state_with_invalid_yield():
  1041. """Test that an error is thrown when a state yields an invalid value."""
  1042. class StateWithInvalidYield(rx.State):
  1043. """A state that yields an invalid value."""
  1044. def invalid_handler(self):
  1045. """Invalid handler.
  1046. Yields:
  1047. an invalid value.
  1048. """
  1049. yield 1
  1050. invalid_state = StateWithInvalidYield()
  1051. with pytest.raises(TypeError) as err:
  1052. invalid_state._check_valid(
  1053. invalid_state.event_handlers["invalid_handler"],
  1054. rx.event.Event(token="fake_token", name="invalid_handler"),
  1055. )
  1056. assert (
  1057. "must only return/yield: None, Events or other EventHandlers"
  1058. in err.value.args[0]
  1059. )