test_state.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  1. from typing import Dict, List
  2. import pytest
  3. from plotly.graph_objects import Figure
  4. import reflex as rx
  5. from reflex.base import Base
  6. from reflex.constants import IS_HYDRATED, RouteVar
  7. from reflex.event import Event, EventHandler
  8. from reflex.state import State
  9. from reflex.utils import format
  10. from reflex.vars import BaseVar, ComputedVar
  11. class Object(Base):
  12. """A test object fixture."""
  13. prop1: int = 42
  14. prop2: str = "hello"
  15. class TestState(State):
  16. """A test state."""
  17. # Set this class as not test one
  18. __test__ = False
  19. num1: int
  20. num2: float = 3.14
  21. key: str
  22. map_key: str = "a"
  23. array: List[float] = [1, 2, 3.14]
  24. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  25. obj: Object = Object()
  26. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  27. fig: Figure = Figure()
  28. @ComputedVar
  29. def sum(self) -> float:
  30. """Dynamically sum the numbers.
  31. Returns:
  32. The sum of the numbers.
  33. """
  34. return self.num1 + self.num2
  35. @ComputedVar
  36. def upper(self) -> str:
  37. """Uppercase the key.
  38. Returns:
  39. The uppercased key.
  40. """
  41. return self.key.upper()
  42. def do_something(self):
  43. """Do something."""
  44. pass
  45. class ChildState(TestState):
  46. """A child state fixture."""
  47. value: str
  48. count: int = 23
  49. def change_both(self, value: str, count: int):
  50. """Change both the value and count.
  51. Args:
  52. value: The new value.
  53. count: The new count.
  54. """
  55. self.value = value.upper()
  56. self.count = count * 2
  57. class ChildState2(TestState):
  58. """A child state fixture."""
  59. value: str
  60. class GrandchildState(ChildState):
  61. """A grandchild state fixture."""
  62. value2: str
  63. def do_nothing(self):
  64. """Do something."""
  65. pass
  66. @pytest.fixture
  67. def test_state() -> TestState:
  68. """A state.
  69. Returns:
  70. A test state.
  71. """
  72. return TestState() # type: ignore
  73. @pytest.fixture
  74. def child_state(test_state) -> ChildState:
  75. """A child state.
  76. Args:
  77. test_state: A test state.
  78. Returns:
  79. A test child state.
  80. """
  81. child_state = test_state.get_substate(["child_state"])
  82. assert child_state is not None
  83. return child_state
  84. @pytest.fixture
  85. def child_state2(test_state) -> ChildState2:
  86. """A second child state.
  87. Args:
  88. test_state: A test state.
  89. Returns:
  90. A second test child state.
  91. """
  92. child_state2 = test_state.get_substate(["child_state2"])
  93. assert child_state2 is not None
  94. return child_state2
  95. @pytest.fixture
  96. def grandchild_state(child_state) -> GrandchildState:
  97. """A state.
  98. Args:
  99. child_state: A child state.
  100. Returns:
  101. A test state.
  102. """
  103. grandchild_state = child_state.get_substate(["grandchild_state"])
  104. assert grandchild_state is not None
  105. return grandchild_state
  106. def test_base_class_vars(test_state):
  107. """Test that the class vars are set correctly.
  108. Args:
  109. test_state: A state.
  110. """
  111. fields = test_state.get_fields()
  112. cls = type(test_state)
  113. for field in fields:
  114. if field in test_state.get_skip_vars():
  115. continue
  116. prop = getattr(cls, field)
  117. assert isinstance(prop, BaseVar)
  118. assert prop.name == field
  119. assert cls.num1.type_ == int
  120. assert cls.num2.type_ == float
  121. assert cls.key.type_ == str
  122. def test_computed_class_var(test_state):
  123. """Test that the class computed vars are set correctly.
  124. Args:
  125. test_state: A state.
  126. """
  127. cls = type(test_state)
  128. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  129. assert ("sum", float) in vars
  130. assert ("upper", str) in vars
  131. def test_class_vars(test_state):
  132. """Test that the class vars are set correctly.
  133. Args:
  134. test_state: A state.
  135. """
  136. cls = type(test_state)
  137. assert set(cls.vars.keys()) == {
  138. IS_HYDRATED, # added by hydrate_middleware to all State
  139. "num1",
  140. "num2",
  141. "key",
  142. "map_key",
  143. "array",
  144. "mapping",
  145. "obj",
  146. "complex",
  147. "sum",
  148. "upper",
  149. "fig",
  150. }
  151. def test_event_handlers(test_state):
  152. """Test that event handler is set correctly.
  153. Args:
  154. test_state: A state.
  155. """
  156. expected = {
  157. "do_something",
  158. "set_array",
  159. "set_complex",
  160. "set_fig",
  161. "set_key",
  162. "set_mapping",
  163. "set_num1",
  164. "set_num2",
  165. "set_obj",
  166. }
  167. cls = type(test_state)
  168. assert set(cls.event_handlers.keys()).intersection(expected) == expected
  169. def test_default_value(test_state):
  170. """Test that the default value of a var is correct.
  171. Args:
  172. test_state: A state.
  173. """
  174. assert test_state.num1 == 0
  175. assert test_state.num2 == 3.14
  176. assert test_state.key == ""
  177. assert test_state.sum == 3.14
  178. assert test_state.upper == ""
  179. def test_computed_vars(test_state):
  180. """Test that the computed var is computed correctly.
  181. Args:
  182. test_state: A state.
  183. """
  184. test_state.num1 = 1
  185. test_state.num2 = 4
  186. assert test_state.sum == 5
  187. test_state.key = "hello world"
  188. assert test_state.upper == "HELLO WORLD"
  189. def test_dict(test_state):
  190. """Test that the dict representation of a state is correct.
  191. Args:
  192. test_state: A state.
  193. """
  194. substates = {"child_state", "child_state2"}
  195. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  196. assert (
  197. set(test_state.dict(include_computed=False).keys())
  198. == set(test_state.base_vars) | substates
  199. )
  200. def test_default_setters(test_state):
  201. """Test that we can set default values.
  202. Args:
  203. test_state: A state.
  204. """
  205. for prop_name in test_state.base_vars:
  206. # Each base var should have a default setter.
  207. assert hasattr(test_state, f"set_{prop_name}")
  208. def test_class_indexing_with_vars():
  209. """Test that we can index into a state var with another var."""
  210. prop = TestState.array[TestState.num1]
  211. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  212. prop = TestState.mapping["a"][TestState.num1]
  213. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  214. prop = TestState.mapping[TestState.map_key]
  215. assert str(prop) == "{test_state.mapping[test_state.map_key]}"
  216. def test_class_attributes():
  217. """Test that we can get class attributes."""
  218. prop = TestState.obj.prop1
  219. assert str(prop) == "{test_state.obj.prop1}"
  220. prop = TestState.complex[1].prop1
  221. assert str(prop) == "{test_state.complex[1].prop1}"
  222. def test_get_parent_state():
  223. """Test getting the parent state."""
  224. assert TestState.get_parent_state() is None
  225. assert ChildState.get_parent_state() == TestState
  226. assert ChildState2.get_parent_state() == TestState
  227. assert GrandchildState.get_parent_state() == ChildState
  228. def test_get_substates():
  229. """Test getting the substates."""
  230. assert TestState.get_substates() == {ChildState, ChildState2}
  231. assert ChildState.get_substates() == {GrandchildState}
  232. assert ChildState2.get_substates() == set()
  233. assert GrandchildState.get_substates() == set()
  234. def test_get_name():
  235. """Test getting the name of a state."""
  236. assert TestState.get_name() == "test_state"
  237. assert ChildState.get_name() == "child_state"
  238. assert ChildState2.get_name() == "child_state2"
  239. assert GrandchildState.get_name() == "grandchild_state"
  240. def test_get_full_name():
  241. """Test getting the full name."""
  242. assert TestState.get_full_name() == "test_state"
  243. assert ChildState.get_full_name() == "test_state.child_state"
  244. assert ChildState2.get_full_name() == "test_state.child_state2"
  245. assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
  246. def test_get_class_substate():
  247. """Test getting the substate of a class."""
  248. assert TestState.get_class_substate(("child_state",)) == ChildState
  249. assert TestState.get_class_substate(("child_state2",)) == ChildState2
  250. assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
  251. assert (
  252. TestState.get_class_substate(("child_state", "grandchild_state"))
  253. == GrandchildState
  254. )
  255. with pytest.raises(ValueError):
  256. TestState.get_class_substate(("invalid_child",))
  257. with pytest.raises(ValueError):
  258. TestState.get_class_substate(
  259. (
  260. "child_state",
  261. "invalid_child",
  262. )
  263. )
  264. def test_get_class_var():
  265. """Test getting the var of a class."""
  266. assert TestState.get_class_var(("num1",)) == TestState.num1
  267. assert TestState.get_class_var(("num2",)) == TestState.num2
  268. assert ChildState.get_class_var(("value",)) == ChildState.value
  269. assert GrandchildState.get_class_var(("value2",)) == GrandchildState.value2
  270. assert TestState.get_class_var(("child_state", "value")) == ChildState.value
  271. assert (
  272. TestState.get_class_var(("child_state", "grandchild_state", "value2"))
  273. == GrandchildState.value2
  274. )
  275. assert (
  276. ChildState.get_class_var(("grandchild_state", "value2"))
  277. == GrandchildState.value2
  278. )
  279. with pytest.raises(ValueError):
  280. TestState.get_class_var(("invalid_var",))
  281. with pytest.raises(ValueError):
  282. TestState.get_class_var(
  283. (
  284. "child_state",
  285. "invalid_var",
  286. )
  287. )
  288. def test_set_class_var():
  289. """Test setting the var of a class."""
  290. with pytest.raises(AttributeError):
  291. TestState.num3 # type: ignore
  292. TestState._set_var(BaseVar(name="num3", type_=int).set_state(TestState))
  293. var = TestState.num3 # type: ignore
  294. assert var.name == "num3"
  295. assert var.type_ == int
  296. assert var.state == TestState.get_full_name()
  297. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  298. """Test setting the parent and substates.
  299. Args:
  300. test_state: A state.
  301. child_state: A child state.
  302. grandchild_state: A grandchild state.
  303. """
  304. assert len(test_state.substates) == 2
  305. assert set(test_state.substates) == {"child_state", "child_state2"}
  306. assert child_state.parent_state == test_state
  307. assert len(child_state.substates) == 1
  308. assert set(child_state.substates) == {"grandchild_state"}
  309. assert grandchild_state.parent_state == child_state
  310. assert len(grandchild_state.substates) == 0
  311. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  312. """Test getting the attribute of a state.
  313. Args:
  314. test_state: A state.
  315. child_state: A child state.
  316. child_state2: A child state.
  317. grandchild_state: A grandchild state.
  318. """
  319. assert test_state.num1 == 0
  320. assert child_state.value == ""
  321. assert child_state2.value == ""
  322. assert child_state.count == 23
  323. assert grandchild_state.value2 == ""
  324. with pytest.raises(AttributeError):
  325. test_state.invalid
  326. with pytest.raises(AttributeError):
  327. test_state.child_state.invalid
  328. with pytest.raises(AttributeError):
  329. test_state.child_state.grandchild_state.invalid
  330. def test_set_child_attribute(test_state, child_state, grandchild_state):
  331. """Test setting the attribute of a state.
  332. Args:
  333. test_state: A state.
  334. child_state: A child state.
  335. grandchild_state: A grandchild state.
  336. """
  337. test_state.num1 = 10
  338. assert test_state.num1 == 10
  339. assert child_state.num1 == 10
  340. assert grandchild_state.num1 == 10
  341. grandchild_state.num1 = 5
  342. assert test_state.num1 == 5
  343. assert child_state.num1 == 5
  344. assert grandchild_state.num1 == 5
  345. child_state.value = "test"
  346. assert child_state.value == "test"
  347. assert grandchild_state.value == "test"
  348. grandchild_state.value = "test2"
  349. assert child_state.value == "test2"
  350. assert grandchild_state.value == "test2"
  351. grandchild_state.value2 = "test3"
  352. assert grandchild_state.value2 == "test3"
  353. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  354. """Test getting the substate of a state.
  355. Args:
  356. test_state: A state.
  357. child_state: A child state.
  358. child_state2: A child state.
  359. grandchild_state: A grandchild state.
  360. """
  361. assert test_state.get_substate(("child_state",)) == child_state
  362. assert test_state.get_substate(("child_state2",)) == child_state2
  363. assert (
  364. test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
  365. )
  366. assert child_state.get_substate(("grandchild_state",)) == grandchild_state
  367. with pytest.raises(ValueError):
  368. test_state.get_substate(("invalid",))
  369. with pytest.raises(ValueError):
  370. test_state.get_substate(("child_state", "invalid"))
  371. with pytest.raises(ValueError):
  372. test_state.get_substate(("child_state", "grandchild_state", "invalid"))
  373. def test_set_dirty_var(test_state):
  374. """Test changing state vars marks the value as dirty.
  375. Args:
  376. test_state: A state.
  377. """
  378. # Initially there should be no dirty vars.
  379. assert test_state.dirty_vars == set()
  380. # Setting a var should mark it as dirty.
  381. test_state.num1 = 1
  382. assert test_state.dirty_vars == {"num1", "sum"}
  383. # Setting another var should mark it as dirty.
  384. test_state.num2 = 2
  385. assert test_state.dirty_vars == {"num1", "num2", "sum"}
  386. # Cleaning the state should remove all dirty vars.
  387. test_state.clean()
  388. assert test_state.dirty_vars == set()
  389. def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
  390. """Test changing substate vars marks the value as dirty.
  391. Args:
  392. test_state: A state.
  393. child_state: A child state.
  394. child_state2: A child state.
  395. grandchild_state: A grandchild state.
  396. """
  397. # Initially there should be no dirty vars.
  398. assert test_state.dirty_vars == set()
  399. assert child_state.dirty_vars == set()
  400. assert child_state2.dirty_vars == set()
  401. assert grandchild_state.dirty_vars == set()
  402. # Setting a var should mark it as dirty.
  403. child_state.value = "test"
  404. assert child_state.dirty_vars == {"value"}
  405. assert test_state.dirty_substates == {"child_state"}
  406. assert child_state.dirty_substates == set()
  407. # Cleaning the parent state should remove the dirty substate.
  408. test_state.clean()
  409. assert test_state.dirty_substates == set()
  410. assert child_state.dirty_vars == set()
  411. # Setting a var on the grandchild should bubble up.
  412. grandchild_state.value2 = "test2"
  413. assert child_state.dirty_substates == {"grandchild_state"}
  414. assert test_state.dirty_substates == {"child_state"}
  415. # Cleaning the middle state should keep the parent state dirty.
  416. child_state.clean()
  417. assert test_state.dirty_substates == {"child_state"}
  418. assert child_state.dirty_substates == set()
  419. assert grandchild_state.dirty_vars == set()
  420. def test_reset(test_state, child_state):
  421. """Test resetting the state.
  422. Args:
  423. test_state: A state.
  424. child_state: A child state.
  425. """
  426. # Set some values.
  427. test_state.num1 = 1
  428. test_state.num2 = 2
  429. child_state.value = "test"
  430. # Reset the state.
  431. test_state.reset()
  432. # The values should be reset.
  433. assert test_state.num1 == 0
  434. assert test_state.num2 == 3.14
  435. assert child_state.value == ""
  436. # The dirty vars should be reset.
  437. assert test_state.dirty_vars == set()
  438. assert child_state.dirty_vars == set()
  439. # The dirty substates should be reset.
  440. assert test_state.dirty_substates == set()
  441. @pytest.mark.asyncio
  442. async def test_process_event_simple(test_state):
  443. """Test processing an event.
  444. Args:
  445. test_state: A state.
  446. """
  447. assert test_state.num1 == 0
  448. event = Event(token="t", name="set_num1", payload={"value": 69})
  449. update = await test_state._process(event).__anext__()
  450. # The event should update the value.
  451. assert test_state.num1 == 69
  452. # The delta should contain the changes, including computed vars.
  453. # assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  454. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14, "upper": ""}}
  455. assert update.events == []
  456. @pytest.mark.asyncio
  457. async def test_process_event_substate(test_state, child_state, grandchild_state):
  458. """Test processing an event on a substate.
  459. Args:
  460. test_state: A state.
  461. child_state: A child state.
  462. grandchild_state: A grandchild state.
  463. """
  464. # Events should bubble down to the substate.
  465. assert child_state.value == ""
  466. assert child_state.count == 23
  467. event = Event(
  468. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  469. )
  470. update = await test_state._process(event).__anext__()
  471. assert child_state.value == "HI"
  472. assert child_state.count == 24
  473. assert update.delta == {
  474. "test_state": {"sum": 3.14, "upper": ""},
  475. "test_state.child_state": {"value": "HI", "count": 24},
  476. }
  477. test_state.clean()
  478. # Test with the granchild state.
  479. assert grandchild_state.value2 == ""
  480. event = Event(
  481. token="t",
  482. name="child_state.grandchild_state.set_value2",
  483. payload={"value": "new"},
  484. )
  485. update = await test_state._process(event).__anext__()
  486. assert grandchild_state.value2 == "new"
  487. assert update.delta == {
  488. "test_state": {"sum": 3.14, "upper": ""},
  489. "test_state.child_state.grandchild_state": {"value2": "new"},
  490. }
  491. @pytest.mark.asyncio
  492. async def test_process_event_generator(gen_state):
  493. """Test event handlers that generate multiple updates.
  494. Args:
  495. gen_state: A state.
  496. """
  497. gen_state = gen_state()
  498. event = Event(
  499. token="t",
  500. name="go",
  501. payload={"c": 5},
  502. )
  503. gen = gen_state._process(event)
  504. count = 0
  505. async for update in gen:
  506. count += 1
  507. if count == 6:
  508. assert update.delta == {}
  509. assert update.final
  510. else:
  511. assert gen_state.value == count
  512. assert update.delta == {
  513. "gen_state": {"value": count},
  514. }
  515. assert not update.final
  516. assert count == 6
  517. def test_format_event_handler():
  518. """Test formatting an event handler."""
  519. assert (
  520. format.format_event_handler(TestState.do_something) == "test_state.do_something" # type: ignore
  521. )
  522. assert (
  523. format.format_event_handler(ChildState.change_both) # type: ignore
  524. == "test_state.child_state.change_both"
  525. )
  526. assert (
  527. format.format_event_handler(GrandchildState.do_nothing) # type: ignore
  528. == "test_state.child_state.grandchild_state.do_nothing"
  529. )
  530. def test_get_token(test_state, mocker, router_data):
  531. """Test that the token obtained from the router_data is correct.
  532. Args:
  533. test_state: The test state.
  534. mocker: Pytest Mocker object.
  535. router_data: The router data fixture.
  536. """
  537. mocker.patch.object(test_state, "router_data", router_data)
  538. assert test_state.get_token() == "b181904c-3953-4a79-dc18-ae9518c22f05"
  539. def test_get_sid(test_state, mocker, router_data):
  540. """Test getting session id.
  541. Args:
  542. test_state: A state.
  543. mocker: Pytest Mocker object.
  544. router_data: The router data fixture.
  545. """
  546. mocker.patch.object(test_state, "router_data", router_data)
  547. assert test_state.get_sid() == "9fpxSzPb9aFMb4wFAAAH"
  548. def test_get_headers(test_state, mocker, router_data, router_data_headers):
  549. """Test getting client headers.
  550. Args:
  551. test_state: A state.
  552. mocker: Pytest Mocker object.
  553. router_data: The router data fixture.
  554. router_data_headers: The expected headers.
  555. """
  556. mocker.patch.object(test_state, "router_data", router_data)
  557. assert test_state.get_headers() == router_data_headers
  558. def test_get_client_ip(test_state, mocker, router_data):
  559. """Test getting client IP.
  560. Args:
  561. test_state: A state.
  562. mocker: Pytest Mocker object.
  563. router_data: The router data fixture.
  564. """
  565. mocker.patch.object(test_state, "router_data", router_data)
  566. assert test_state.get_client_ip() == "127.0.0.1"
  567. def test_get_cookies(test_state, mocker, router_data):
  568. """Test getting client cookies.
  569. Args:
  570. test_state: A state.
  571. mocker: Pytest Mocker object.
  572. router_data: The router data fixture.
  573. """
  574. mocker.patch.object(test_state, "router_data", router_data)
  575. assert test_state.get_cookies() == {
  576. "csrftoken": "mocktoken",
  577. "name": "reflex",
  578. "list_cookies": ["some", "random", "cookies"],
  579. "dict_cookies": {"name": "reflex"},
  580. "val": True,
  581. }
  582. def test_get_current_page(test_state):
  583. assert test_state.get_current_page() == ""
  584. route = "mypage/subpage"
  585. test_state.router_data = {RouteVar.PATH: route}
  586. assert test_state.get_current_page() == route
  587. def test_get_query_params(test_state):
  588. assert test_state.get_query_params() == {}
  589. params = {"p1": "a", "p2": "b"}
  590. test_state.router_data = {RouteVar.QUERY: params}
  591. assert test_state.get_query_params() == params
  592. def test_add_var(test_state):
  593. test_state.add_var("dynamic_int", int, 42)
  594. assert test_state.dynamic_int == 42
  595. test_state.add_var("dynamic_list", List[int], [5, 10])
  596. assert test_state.dynamic_list == [5, 10]
  597. assert test_state.dynamic_list == [5, 10]
  598. # how to test that one?
  599. # test_state.dynamic_list.append(15)
  600. # assert test_state.dynamic_list == [5, 10, 15]
  601. test_state.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  602. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  603. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  604. def test_add_var_default_handlers(test_state):
  605. test_state.add_var("rand_int", int, 10)
  606. assert "set_rand_int" in test_state.event_handlers
  607. assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
  608. class InterdependentState(State):
  609. """A state with 3 vars and 3 computed vars.
  610. x: a variable that no computed var depends on
  611. v1: a varable that one computed var directly depeneds on
  612. _v2: a backend variable that one computed var directly depends on
  613. v1x2: a computed var that depends on v1
  614. v2x2: a computed var that depends on backend var _v2
  615. v1x2x2: a computed var that depends on computed var v1x2
  616. """
  617. x: int = 0
  618. v1: int = 0
  619. _v2: int = 1
  620. @rx.cached_var
  621. def v1x2(self) -> int:
  622. """Depends on var v1.
  623. Returns:
  624. Var v1 multiplied by 2
  625. """
  626. return self.v1 * 2
  627. @rx.cached_var
  628. def v2x2(self) -> int:
  629. """Depends on backend var _v2.
  630. Returns:
  631. backend var _v2 multiplied by 2
  632. """
  633. return self._v2 * 2
  634. @rx.cached_var
  635. def v1x2x2(self) -> int:
  636. """Depends on ComputedVar v1x2.
  637. Returns:
  638. ComputedVar v1x2 multiplied by 2
  639. """
  640. return self.v1x2 * 2
  641. @pytest.fixture
  642. def interdependent_state() -> State:
  643. """A state with varying dependency between vars.
  644. Returns:
  645. instance of InterdependentState
  646. """
  647. s = InterdependentState()
  648. s.dict() # prime initial relationships by accessing all ComputedVars
  649. return s
  650. def test_not_dirty_computed_var_from_var(interdependent_state):
  651. """Set Var that no ComputedVar depends on, expect no recalculation.
  652. Args:
  653. interdependent_state: A state with varying Var dependencies.
  654. """
  655. interdependent_state.x = 5
  656. assert interdependent_state.get_delta() == {
  657. interdependent_state.get_full_name(): {"x": 5},
  658. }
  659. def test_dirty_computed_var_from_var(interdependent_state):
  660. """Set Var that ComputedVar depends on, expect recalculation.
  661. The other ComputedVar depends on the changed ComputedVar and should also be
  662. recalculated. No other ComputedVars should be recalculated.
  663. Args:
  664. interdependent_state: A state with varying Var dependencies.
  665. """
  666. interdependent_state.v1 = 1
  667. assert interdependent_state.get_delta() == {
  668. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  669. }
  670. def test_dirty_computed_var_from_backend_var(interdependent_state):
  671. """Set backend var that ComputedVar depends on, expect recalculation.
  672. Args:
  673. interdependent_state: A state with varying Var dependencies.
  674. """
  675. interdependent_state._v2 = 2
  676. assert interdependent_state.get_delta() == {
  677. interdependent_state.get_full_name(): {"v2x2": 4},
  678. }
  679. def test_per_state_backend_var(interdependent_state):
  680. """Set backend var on one instance, expect no affect in other instances.
  681. Args:
  682. interdependent_state: A state with varying Var dependencies.
  683. """
  684. s2 = InterdependentState()
  685. assert s2._v2 == interdependent_state._v2
  686. interdependent_state._v2 = 2
  687. assert s2._v2 != interdependent_state._v2
  688. s3 = InterdependentState()
  689. assert s3._v2 != interdependent_state._v2
  690. # both s2 and s3 should still have the default value
  691. assert s2._v2 == s3._v2
  692. # changing s2._v2 should not affect others
  693. s2._v2 = 4
  694. assert s2._v2 != interdependent_state._v2
  695. assert s2._v2 != s3._v2
  696. def test_child_state():
  697. """Test that the child state computed vars can reference parent state vars."""
  698. class MainState(State):
  699. v: int = 2
  700. class ChildState(MainState):
  701. @ComputedVar
  702. def rendered_var(self):
  703. return self.v
  704. ms = MainState()
  705. cs = ms.substates[ChildState.get_name()]
  706. assert ms.v == 2
  707. assert cs.v == 2
  708. assert cs.rendered_var == 2
  709. def test_conditional_computed_vars():
  710. """Test that computed vars can have conditionals."""
  711. class MainState(State):
  712. flag: bool = False
  713. t1: str = "a"
  714. t2: str = "b"
  715. @ComputedVar
  716. def rendered_var(self) -> str:
  717. if self.flag:
  718. return self.t1
  719. return self.t2
  720. ms = MainState()
  721. # Initially there are no dirty computed vars.
  722. assert ms._dirty_computed_vars(from_vars={"flag"}) == {"rendered_var"}
  723. assert ms._dirty_computed_vars(from_vars={"t2"}) == {"rendered_var"}
  724. assert ms._dirty_computed_vars(from_vars={"t1"}) == {"rendered_var"}
  725. assert ms.computed_vars["rendered_var"].deps(objclass=MainState) == {
  726. "flag",
  727. "t1",
  728. "t2",
  729. }
  730. def test_event_handlers_convert_to_fns(test_state, child_state):
  731. """Test that when the state is initialized, event handlers are converted to fns.
  732. Args:
  733. test_state: A state with event handlers.
  734. child_state: A child state with event handlers.
  735. """
  736. # The class instances should be event handlers.
  737. assert isinstance(TestState.do_something, EventHandler)
  738. assert isinstance(ChildState.change_both, EventHandler)
  739. # The object instances should be fns.
  740. test_state.do_something()
  741. child_state.change_both(value="goose", count=9)
  742. assert child_state.value == "GOOSE"
  743. assert child_state.count == 18
  744. def test_event_handlers_call_other_handlers():
  745. """Test that event handlers can call other event handlers."""
  746. class MainState(State):
  747. v: int = 0
  748. def set_v(self, v: int):
  749. self.v = v
  750. def set_v2(self, v: int):
  751. self.set_v(v)
  752. ms = MainState()
  753. ms.set_v2(1)
  754. assert ms.v == 1
  755. def test_computed_var_cached():
  756. """Test that a ComputedVar doesn't recalculate when accessed."""
  757. comp_v_calls = 0
  758. class ComputedState(State):
  759. v: int = 0
  760. @rx.cached_var
  761. def comp_v(self) -> int:
  762. nonlocal comp_v_calls
  763. comp_v_calls += 1
  764. return self.v
  765. cs = ComputedState()
  766. assert cs.dict()["v"] == 0
  767. assert comp_v_calls == 1
  768. assert cs.dict()["comp_v"] == 0
  769. assert comp_v_calls == 1
  770. assert cs.comp_v == 0
  771. assert comp_v_calls == 1
  772. cs.v = 1
  773. assert comp_v_calls == 1
  774. assert cs.comp_v == 1
  775. assert comp_v_calls == 2
  776. def test_computed_var_cached_depends_on_non_cached():
  777. """Test that a cached_var is recalculated if it depends on non-cached ComputedVar."""
  778. class ComputedState(State):
  779. v: int = 0
  780. @rx.var
  781. def no_cache_v(self) -> int:
  782. return self.v
  783. @rx.cached_var
  784. def dep_v(self) -> int:
  785. return self.no_cache_v
  786. @rx.cached_var
  787. def comp_v(self) -> int:
  788. return self.v
  789. cs = ComputedState()
  790. assert cs.dirty_vars == set()
  791. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  792. cs.clean()
  793. assert cs.dirty_vars == set()
  794. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  795. cs.clean()
  796. assert cs.dirty_vars == set()
  797. cs.v = 1
  798. assert cs.dirty_vars == {"v", "comp_v", "dep_v", "no_cache_v"}
  799. assert cs.get_delta() == {
  800. cs.get_name(): {"v": 1, "no_cache_v": 1, "dep_v": 1, "comp_v": 1}
  801. }
  802. cs.clean()
  803. assert cs.dirty_vars == set()
  804. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  805. cs.clean()
  806. assert cs.dirty_vars == set()
  807. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  808. cs.clean()
  809. assert cs.dirty_vars == set()
  810. def test_computed_var_depends_on_parent_non_cached():
  811. """Child state cached_var that depends on parent state un cached var is always recalculated."""
  812. counter = 0
  813. class ParentState(State):
  814. @rx.var
  815. def no_cache_v(self) -> int:
  816. nonlocal counter
  817. counter += 1
  818. return counter
  819. class ChildState(ParentState):
  820. @rx.cached_var
  821. def dep_v(self) -> int:
  822. return self.no_cache_v
  823. ps = ParentState()
  824. cs = ps.substates[ChildState.get_name()]
  825. assert ps.dirty_vars == set()
  826. assert cs.dirty_vars == set()
  827. assert ps.dict() == {
  828. cs.get_name(): {"dep_v": 2},
  829. "no_cache_v": 1,
  830. IS_HYDRATED: False,
  831. }
  832. assert ps.dict() == {
  833. cs.get_name(): {"dep_v": 4},
  834. "no_cache_v": 3,
  835. IS_HYDRATED: False,
  836. }
  837. assert ps.dict() == {
  838. cs.get_name(): {"dep_v": 6},
  839. "no_cache_v": 5,
  840. IS_HYDRATED: False,
  841. }
  842. assert counter == 6