test_state.py 31 KB

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