test_state.py 29 KB

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