test_state.py 36 KB

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