test_state.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831
  1. from typing import Dict, List
  2. import pytest
  3. from plotly.graph_objects import Figure
  4. from pynecone.base import Base
  5. from pynecone.constants import RouteVar
  6. from pynecone.event import Event
  7. from pynecone.middleware.hydrate_middleware import IS_HYDRATED
  8. from pynecone.state import State
  9. from pynecone.utils import format
  10. from pynecone.var 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. array: List[float] = [1, 2, 3.14]
  23. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  24. obj: Object = Object()
  25. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  26. fig: Figure = Figure()
  27. @ComputedVar
  28. def sum(self) -> float:
  29. """Dynamically sum the numbers.
  30. Returns:
  31. The sum of the numbers.
  32. """
  33. return self.num1 + self.num2
  34. @ComputedVar
  35. def upper(self) -> str:
  36. """Uppercase the key.
  37. Returns:
  38. The uppercased key.
  39. """
  40. return self.key.upper()
  41. def do_something(self):
  42. """Do something."""
  43. pass
  44. class ChildState(TestState):
  45. """A child state fixture."""
  46. value: str
  47. count: int = 23
  48. def change_both(self, value: str, count: int):
  49. """Change both the value and count.
  50. Args:
  51. value: The new value.
  52. count: The new count.
  53. """
  54. self.value = value.upper()
  55. self.count = count * 2
  56. class ChildState2(TestState):
  57. """A child state fixture."""
  58. value: str
  59. class GrandchildState(ChildState):
  60. """A grandchild state fixture."""
  61. value2: str
  62. def do_nothing(self):
  63. """Do something."""
  64. pass
  65. @pytest.fixture
  66. def test_state() -> TestState:
  67. """A state.
  68. Returns:
  69. A test state.
  70. """
  71. return TestState() # type: ignore
  72. @pytest.fixture
  73. def child_state(test_state) -> ChildState:
  74. """A child state.
  75. Args:
  76. test_state: A test state.
  77. Returns:
  78. A test child state.
  79. """
  80. child_state = test_state.get_substate(["child_state"])
  81. assert child_state is not None
  82. return child_state
  83. @pytest.fixture
  84. def child_state2(test_state) -> ChildState2:
  85. """A second child state.
  86. Args:
  87. test_state: A test state.
  88. Returns:
  89. A second test child state.
  90. """
  91. child_state2 = test_state.get_substate(["child_state2"])
  92. assert child_state2 is not None
  93. return child_state2
  94. @pytest.fixture
  95. def grandchild_state(child_state) -> GrandchildState:
  96. """A state.
  97. Args:
  98. child_state: A child state.
  99. Returns:
  100. A test state.
  101. """
  102. grandchild_state = child_state.get_substate(["grandchild_state"])
  103. assert grandchild_state is not None
  104. return grandchild_state
  105. def test_base_class_vars(test_state):
  106. """Test that the class vars are set correctly.
  107. Args:
  108. test_state: A state.
  109. """
  110. fields = test_state.get_fields()
  111. cls = type(test_state)
  112. for field in fields:
  113. if field in test_state.get_skip_vars():
  114. continue
  115. prop = getattr(cls, field)
  116. assert isinstance(prop, BaseVar)
  117. assert prop.name == field
  118. assert cls.num1.type_ == int
  119. assert cls.num2.type_ == float
  120. assert cls.key.type_ == str
  121. def test_computed_class_var(test_state):
  122. """Test that the class computed vars are set correctly.
  123. Args:
  124. test_state: A state.
  125. """
  126. cls = type(test_state)
  127. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  128. assert ("sum", float) in vars
  129. assert ("upper", str) in vars
  130. def test_class_vars(test_state):
  131. """Test that the class vars are set correctly.
  132. Args:
  133. test_state: A state.
  134. """
  135. cls = type(test_state)
  136. assert set(cls.vars.keys()) == {
  137. IS_HYDRATED, # added by hydrate_middleware to all State
  138. "num1",
  139. "num2",
  140. "key",
  141. "array",
  142. "mapping",
  143. "obj",
  144. "complex",
  145. "sum",
  146. "upper",
  147. "fig",
  148. }
  149. def test_event_handlers(test_state):
  150. """Test that event handler is set correctly.
  151. Args:
  152. test_state: A state.
  153. """
  154. expected = {
  155. "do_something",
  156. "set_array",
  157. "set_complex",
  158. "set_fig",
  159. "set_key",
  160. "set_mapping",
  161. "set_num1",
  162. "set_num2",
  163. "set_obj",
  164. }
  165. cls = type(test_state)
  166. assert set(cls.event_handlers.keys()).intersection(expected) == expected
  167. def test_default_value(test_state):
  168. """Test that the default value of a var is correct.
  169. Args:
  170. test_state: A state.
  171. """
  172. assert test_state.num1 == 0
  173. assert test_state.num2 == 3.14
  174. assert test_state.key == ""
  175. assert test_state.sum == 3.14
  176. assert test_state.upper == ""
  177. def test_computed_vars(test_state):
  178. """Test that the computed var is computed correctly.
  179. Args:
  180. test_state: A state.
  181. """
  182. test_state.num1 = 1
  183. test_state.num2 = 4
  184. assert test_state.sum == 5
  185. test_state.key = "hello world"
  186. assert test_state.upper == "HELLO WORLD"
  187. def test_dict(test_state):
  188. """Test that the dict representation of a state is correct.
  189. Args:
  190. test_state: A state.
  191. """
  192. substates = {"child_state", "child_state2"}
  193. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  194. assert (
  195. set(test_state.dict(include_computed=False).keys())
  196. == set(test_state.base_vars) | substates
  197. )
  198. def test_default_setters(test_state):
  199. """Test that we can set default values.
  200. Args:
  201. test_state: A state.
  202. """
  203. for prop_name in test_state.base_vars:
  204. # Each base var should have a default setter.
  205. assert hasattr(test_state, f"set_{prop_name}")
  206. def test_class_indexing_with_vars():
  207. """Test that we can index into a state var with another var."""
  208. prop = TestState.array[TestState.num1]
  209. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  210. prop = TestState.mapping["a"][TestState.num1]
  211. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  212. def test_class_attributes():
  213. """Test that we can get class attributes."""
  214. prop = TestState.obj.prop1
  215. assert str(prop) == "{test_state.obj.prop1}"
  216. prop = TestState.complex[1].prop1
  217. assert str(prop) == "{test_state.complex[1].prop1}"
  218. def test_get_parent_state():
  219. """Test getting the parent state."""
  220. assert TestState.get_parent_state() is None
  221. assert ChildState.get_parent_state() == TestState
  222. assert ChildState2.get_parent_state() == TestState
  223. assert GrandchildState.get_parent_state() == ChildState
  224. def test_get_substates():
  225. """Test getting the substates."""
  226. assert TestState.get_substates() == {ChildState, ChildState2}
  227. assert ChildState.get_substates() == {GrandchildState}
  228. assert ChildState2.get_substates() == set()
  229. assert GrandchildState.get_substates() == set()
  230. def test_get_name():
  231. """Test getting the name of a state."""
  232. assert TestState.get_name() == "test_state"
  233. assert ChildState.get_name() == "child_state"
  234. assert ChildState2.get_name() == "child_state2"
  235. assert GrandchildState.get_name() == "grandchild_state"
  236. def test_get_full_name():
  237. """Test getting the full name."""
  238. assert TestState.get_full_name() == "test_state"
  239. assert ChildState.get_full_name() == "test_state.child_state"
  240. assert ChildState2.get_full_name() == "test_state.child_state2"
  241. assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
  242. def test_get_class_substate():
  243. """Test getting the substate of a class."""
  244. assert TestState.get_class_substate(("child_state",)) == ChildState
  245. assert TestState.get_class_substate(("child_state2",)) == ChildState2
  246. assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
  247. assert (
  248. TestState.get_class_substate(("child_state", "grandchild_state"))
  249. == GrandchildState
  250. )
  251. with pytest.raises(ValueError):
  252. TestState.get_class_substate(("invalid_child",))
  253. with pytest.raises(ValueError):
  254. TestState.get_class_substate(
  255. (
  256. "child_state",
  257. "invalid_child",
  258. )
  259. )
  260. def test_get_class_var():
  261. """Test getting the var of a class."""
  262. assert TestState.get_class_var(("num1",)) == TestState.num1
  263. assert TestState.get_class_var(("num2",)) == TestState.num2
  264. assert ChildState.get_class_var(("value",)) == ChildState.value
  265. assert GrandchildState.get_class_var(("value2",)) == GrandchildState.value2
  266. assert TestState.get_class_var(("child_state", "value")) == ChildState.value
  267. assert (
  268. TestState.get_class_var(("child_state", "grandchild_state", "value2"))
  269. == GrandchildState.value2
  270. )
  271. assert (
  272. ChildState.get_class_var(("grandchild_state", "value2"))
  273. == GrandchildState.value2
  274. )
  275. with pytest.raises(ValueError):
  276. TestState.get_class_var(("invalid_var",))
  277. with pytest.raises(ValueError):
  278. TestState.get_class_var(
  279. (
  280. "child_state",
  281. "invalid_var",
  282. )
  283. )
  284. def test_set_class_var():
  285. """Test setting the var of a class."""
  286. with pytest.raises(AttributeError):
  287. TestState.num3 # type: ignore
  288. TestState._set_var(BaseVar(name="num3", type_=int).set_state(TestState))
  289. var = TestState.num3 # type: ignore
  290. assert var.name == "num3"
  291. assert var.type_ == int
  292. assert var.state == TestState.get_full_name()
  293. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  294. """Test setting the parent and substates.
  295. Args:
  296. test_state: A state.
  297. child_state: A child state.
  298. grandchild_state: A grandchild state.
  299. """
  300. assert len(test_state.substates) == 2
  301. assert set(test_state.substates) == {"child_state", "child_state2"}
  302. assert child_state.parent_state == test_state
  303. assert len(child_state.substates) == 1
  304. assert set(child_state.substates) == {"grandchild_state"}
  305. assert grandchild_state.parent_state == child_state
  306. assert len(grandchild_state.substates) == 0
  307. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  308. """Test getting the attribute of a state.
  309. Args:
  310. test_state: A state.
  311. child_state: A child state.
  312. child_state2: A child state.
  313. grandchild_state: A grandchild state.
  314. """
  315. assert test_state.num1 == 0
  316. assert child_state.value == ""
  317. assert child_state2.value == ""
  318. assert child_state.count == 23
  319. assert grandchild_state.value2 == ""
  320. with pytest.raises(AttributeError):
  321. test_state.invalid
  322. with pytest.raises(AttributeError):
  323. test_state.child_state.invalid
  324. with pytest.raises(AttributeError):
  325. test_state.child_state.grandchild_state.invalid
  326. def test_set_child_attribute(test_state, child_state, grandchild_state):
  327. """Test setting the attribute of a state.
  328. Args:
  329. test_state: A state.
  330. child_state: A child state.
  331. grandchild_state: A grandchild state.
  332. """
  333. test_state.num1 = 10
  334. assert test_state.num1 == 10
  335. assert child_state.num1 == 10
  336. assert grandchild_state.num1 == 10
  337. grandchild_state.num1 = 5
  338. assert test_state.num1 == 5
  339. assert child_state.num1 == 5
  340. assert grandchild_state.num1 == 5
  341. child_state.value = "test"
  342. assert child_state.value == "test"
  343. assert grandchild_state.value == "test"
  344. grandchild_state.value = "test2"
  345. assert child_state.value == "test2"
  346. assert grandchild_state.value == "test2"
  347. grandchild_state.value2 = "test3"
  348. assert grandchild_state.value2 == "test3"
  349. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  350. """Test getting the substate of a state.
  351. Args:
  352. test_state: A state.
  353. child_state: A child state.
  354. child_state2: A child state.
  355. grandchild_state: A grandchild state.
  356. """
  357. assert test_state.get_substate(("child_state",)) == child_state
  358. assert test_state.get_substate(("child_state2",)) == child_state2
  359. assert (
  360. test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
  361. )
  362. assert child_state.get_substate(("grandchild_state",)) == grandchild_state
  363. with pytest.raises(ValueError):
  364. test_state.get_substate(("invalid",))
  365. with pytest.raises(ValueError):
  366. test_state.get_substate(("child_state", "invalid"))
  367. with pytest.raises(ValueError):
  368. test_state.get_substate(("child_state", "grandchild_state", "invalid"))
  369. def test_set_dirty_var(test_state):
  370. """Test changing state vars marks the value as dirty.
  371. Args:
  372. test_state: A state.
  373. """
  374. # Initially there should be no dirty vars.
  375. assert test_state.dirty_vars == set()
  376. # Setting a var should mark it as dirty.
  377. test_state.num1 = 1
  378. assert test_state.dirty_vars == {"num1"}
  379. # Setting another var should mark it as dirty.
  380. test_state.num2 = 2
  381. assert test_state.dirty_vars == {"num1", "num2"}
  382. # Cleaning the state should remove all dirty vars.
  383. test_state.clean()
  384. assert test_state.dirty_vars == set()
  385. def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
  386. """Test changing substate vars marks the value as dirty.
  387. Args:
  388. test_state: A state.
  389. child_state: A child state.
  390. child_state2: A child state.
  391. grandchild_state: A grandchild state.
  392. """
  393. # Initially there should be no dirty vars.
  394. assert test_state.dirty_vars == set()
  395. assert child_state.dirty_vars == set()
  396. assert child_state2.dirty_vars == set()
  397. assert grandchild_state.dirty_vars == set()
  398. # Setting a var should mark it as dirty.
  399. child_state.value = "test"
  400. assert child_state.dirty_vars == {"value"}
  401. assert test_state.dirty_substates == {"child_state"}
  402. assert child_state.dirty_substates == set()
  403. # Cleaning the parent state should remove the dirty substate.
  404. test_state.clean()
  405. assert test_state.dirty_substates == set()
  406. assert child_state.dirty_vars == set()
  407. # Setting a var on the grandchild should bubble up.
  408. grandchild_state.value2 = "test2"
  409. assert child_state.dirty_substates == {"grandchild_state"}
  410. assert test_state.dirty_substates == {"child_state"}
  411. # Cleaning the middle state should keep the parent state dirty.
  412. child_state.clean()
  413. assert test_state.dirty_substates == {"child_state"}
  414. assert child_state.dirty_substates == set()
  415. assert grandchild_state.dirty_vars == set()
  416. def test_reset(test_state, child_state):
  417. """Test resetting the state.
  418. Args:
  419. test_state: A state.
  420. child_state: A child state.
  421. """
  422. # Set some values.
  423. test_state.num1 = 1
  424. test_state.num2 = 2
  425. child_state.value = "test"
  426. # Reset the state.
  427. test_state.reset()
  428. # The values should be reset.
  429. assert test_state.num1 == 0
  430. assert test_state.num2 == 3.14
  431. assert child_state.value == ""
  432. # The dirty vars should be reset.
  433. assert test_state.dirty_vars == set()
  434. assert child_state.dirty_vars == set()
  435. # The dirty substates should be reset.
  436. assert test_state.dirty_substates == set()
  437. @pytest.mark.asyncio
  438. async def test_process_event_simple(test_state):
  439. """Test processing an event.
  440. Args:
  441. test_state: A state.
  442. """
  443. assert test_state.num1 == 0
  444. event = Event(token="t", name="set_num1", payload={"value": 69})
  445. update = await test_state._process(event)
  446. # The event should update the value.
  447. assert test_state.num1 == 69
  448. # The delta should contain the changes, including computed vars.
  449. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  450. assert update.events == []
  451. @pytest.mark.asyncio
  452. async def test_process_event_substate(test_state, child_state, grandchild_state):
  453. """Test processing an event on a substate.
  454. Args:
  455. test_state: A state.
  456. child_state: A child state.
  457. grandchild_state: A grandchild state.
  458. """
  459. # Events should bubble down to the substate.
  460. assert child_state.value == ""
  461. assert child_state.count == 23
  462. event = Event(
  463. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  464. )
  465. update = await test_state._process(event)
  466. assert child_state.value == "HI"
  467. assert child_state.count == 24
  468. assert update.delta == {
  469. "test_state.child_state": {"value": "HI", "count": 24},
  470. }
  471. test_state.clean()
  472. # Test with the granchild state.
  473. assert grandchild_state.value2 == ""
  474. event = Event(
  475. token="t",
  476. name="child_state.grandchild_state.set_value2",
  477. payload={"value": "new"},
  478. )
  479. update = await test_state._process(event)
  480. assert grandchild_state.value2 == "new"
  481. assert update.delta == {
  482. "test_state.child_state.grandchild_state": {"value2": "new"},
  483. }
  484. def test_format_event_handler():
  485. """Test formatting an event handler."""
  486. assert (
  487. format.format_event_handler(TestState.do_something) == "test_state.do_something" # type: ignore
  488. )
  489. assert (
  490. format.format_event_handler(ChildState.change_both) # type: ignore
  491. == "test_state.child_state.change_both"
  492. )
  493. assert (
  494. format.format_event_handler(GrandchildState.do_nothing) # type: ignore
  495. == "test_state.child_state.grandchild_state.do_nothing"
  496. )
  497. def test_get_token(test_state):
  498. assert test_state.get_token() == ""
  499. token = "b181904c-3953-4a79-dc18-ae9518c22f05"
  500. test_state.router_data = {RouteVar.CLIENT_TOKEN: token}
  501. assert test_state.get_token() == token
  502. def test_get_sid(test_state):
  503. """Test getting session id.
  504. Args:
  505. test_state: A state.
  506. """
  507. assert test_state.get_sid() == ""
  508. sid = "9fpxSzPb9aFMb4wFAAAH"
  509. test_state.router_data = {RouteVar.SESSION_ID: sid}
  510. assert test_state.get_sid() == sid
  511. def test_get_headers(test_state):
  512. """Test getting client headers.
  513. Args:
  514. test_state: A state.
  515. """
  516. assert test_state.get_headers() == {}
  517. headers = {"host": "localhost:8000", "connection": "keep-alive"}
  518. test_state.router_data = {RouteVar.HEADERS: headers}
  519. assert test_state.get_headers() == headers
  520. def test_get_client_ip(test_state):
  521. """Test getting client IP.
  522. Args:
  523. test_state: A state.
  524. """
  525. assert test_state.get_client_ip() == ""
  526. client_ip = "127.0.0.1"
  527. test_state.router_data = {RouteVar.CLIENT_IP: client_ip}
  528. assert test_state.get_client_ip() == client_ip
  529. def test_get_current_page(test_state):
  530. assert test_state.get_current_page() == ""
  531. route = "mypage/subpage"
  532. test_state.router_data = {RouteVar.PATH: route}
  533. assert test_state.get_current_page() == route
  534. def test_get_query_params(test_state):
  535. assert test_state.get_query_params() == {}
  536. params = {"p1": "a", "p2": "b"}
  537. test_state.router_data = {RouteVar.QUERY: params}
  538. assert test_state.get_query_params() == params
  539. def test_add_var(test_state):
  540. test_state.add_var("dynamic_int", int, 42)
  541. assert test_state.dynamic_int == 42
  542. test_state.add_var("dynamic_list", List[int], [5, 10])
  543. assert test_state.dynamic_list == [5, 10]
  544. assert test_state.dynamic_list == [5, 10]
  545. # how to test that one?
  546. # test_state.dynamic_list.append(15)
  547. # assert test_state.dynamic_list == [5, 10, 15]
  548. test_state.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  549. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  550. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  551. class InterdependentState(State):
  552. """A state with 3 vars and 3 computed vars.
  553. x: a variable that no computed var depends on
  554. v1: a varable that one computed var directly depeneds on
  555. _v2: a backend variable that one computed var directly depends on
  556. v1x2: a computed var that depends on v1
  557. v2x2: a computed var that depends on backend var _v2
  558. v1x2x2: a computed var that depends on computed var v1x2
  559. """
  560. x: int = 0
  561. v1: int = 0
  562. _v2: int = 1
  563. @ComputedVar
  564. def v1x2(self) -> int:
  565. """depends on var v1.
  566. Returns:
  567. Var v1 multiplied by 2
  568. """
  569. return self.v1 * 2
  570. @ComputedVar
  571. def v2x2(self) -> int:
  572. """depends on backend var _v2.
  573. Returns:
  574. backend var _v2 multiplied by 2
  575. """
  576. return self._v2 * 2
  577. @ComputedVar
  578. def v1x2x2(self) -> int:
  579. """depends on ComputedVar v1x2.
  580. Returns:
  581. ComputedVar v1x2 multiplied by 2
  582. """
  583. return self.v1x2 * 2
  584. @pytest.fixture
  585. def interdependent_state() -> State:
  586. """A state with varying dependency between vars.
  587. Returns:
  588. instance of InterdependentState
  589. """
  590. s = InterdependentState()
  591. s.dict() # prime initial relationships by accessing all ComputedVars
  592. return s
  593. def test_not_dirty_computed_var_from_var(interdependent_state):
  594. """Set Var that no ComputedVar depends on, expect no recalculation.
  595. Args:
  596. interdependent_state: A state with varying Var dependencies.
  597. """
  598. interdependent_state.x = 5
  599. assert interdependent_state.get_delta() == {
  600. interdependent_state.get_full_name(): {"x": 5},
  601. }
  602. def test_dirty_computed_var_from_var(interdependent_state):
  603. """Set Var that ComputedVar depends on, expect recalculation.
  604. The other ComputedVar depends on the changed ComputedVar and should also be
  605. recalculated. No other ComputedVars should be recalculated.
  606. Args:
  607. interdependent_state: A state with varying Var dependencies.
  608. """
  609. interdependent_state.v1 = 1
  610. assert interdependent_state.get_delta() == {
  611. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  612. }
  613. def test_dirty_computed_var_from_backend_var(interdependent_state):
  614. """Set backend var that ComputedVar depends on, expect recalculation.
  615. Args:
  616. interdependent_state: A state with varying Var dependencies.
  617. """
  618. interdependent_state._v2 = 2
  619. assert interdependent_state.get_delta() == {
  620. interdependent_state.get_full_name(): {"v2x2": 4},
  621. }
  622. def test_child_state():
  623. class MainState(State):
  624. v: int = 2
  625. class ChildState(MainState):
  626. @ComputedVar
  627. def rendered_var(self):
  628. return self.v
  629. ms = MainState()
  630. cs = ms.substates[ChildState.get_name()]
  631. assert ms.v == 2
  632. assert cs.v == 2
  633. assert cs.rendered_var == 2