test_state.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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 (
  114. "parent_state",
  115. "substates",
  116. "dirty_vars",
  117. "dirty_substates",
  118. "router_data",
  119. ):
  120. continue
  121. prop = getattr(cls, field)
  122. assert isinstance(prop, BaseVar)
  123. assert prop.name == field
  124. assert cls.num1.type_ == int
  125. assert cls.num2.type_ == float
  126. assert cls.key.type_ == str
  127. def test_computed_class_var(test_state):
  128. """Test that the class computed vars are set correctly.
  129. Args:
  130. test_state: A state.
  131. """
  132. cls = type(test_state)
  133. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  134. assert ("sum", float) in vars
  135. assert ("upper", str) in vars
  136. def test_class_vars(test_state):
  137. """Test that the class vars are set correctly.
  138. Args:
  139. test_state: A state.
  140. """
  141. cls = type(test_state)
  142. assert set(cls.vars.keys()) == {
  143. IS_HYDRATED, # added by hydrate_middleware to all State
  144. "num1",
  145. "num2",
  146. "key",
  147. "array",
  148. "mapping",
  149. "obj",
  150. "complex",
  151. "sum",
  152. "upper",
  153. "fig",
  154. }
  155. def test_event_handlers(test_state):
  156. """Test that event handler is set correctly.
  157. Args:
  158. test_state: A state.
  159. """
  160. expected = {
  161. "do_something",
  162. "set_array",
  163. "set_complex",
  164. "set_fig",
  165. "set_key",
  166. "set_mapping",
  167. "set_num1",
  168. "set_num2",
  169. "set_obj",
  170. }
  171. cls = type(test_state)
  172. assert set(cls.event_handlers.keys()).intersection(expected) == expected
  173. def test_default_value(test_state):
  174. """Test that the default value of a var is correct.
  175. Args:
  176. test_state: A state.
  177. """
  178. assert test_state.num1 == 0
  179. assert test_state.num2 == 3.14
  180. assert test_state.key == ""
  181. assert test_state.sum == 3.14
  182. assert test_state.upper == ""
  183. def test_computed_vars(test_state):
  184. """Test that the computed var is computed correctly.
  185. Args:
  186. test_state: A state.
  187. """
  188. test_state.num1 = 1
  189. test_state.num2 = 4
  190. assert test_state.sum == 5
  191. test_state.key = "hello world"
  192. assert test_state.upper == "HELLO WORLD"
  193. def test_dict(test_state):
  194. """Test that the dict representation of a state is correct.
  195. Args:
  196. test_state: A state.
  197. """
  198. substates = {"child_state", "child_state2"}
  199. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  200. assert (
  201. set(test_state.dict(include_computed=False).keys())
  202. == set(test_state.base_vars) | substates
  203. )
  204. def test_default_setters(test_state):
  205. """Test that we can set default values.
  206. Args:
  207. test_state: A state.
  208. """
  209. for prop_name in test_state.base_vars:
  210. # Each base var should have a default setter.
  211. assert hasattr(test_state, f"set_{prop_name}")
  212. def test_class_indexing_with_vars():
  213. """Test that we can index into a state var with another var."""
  214. prop = TestState.array[TestState.num1]
  215. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  216. prop = TestState.mapping["a"][TestState.num1]
  217. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  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"}
  385. # Setting another var should mark it as dirty.
  386. test_state.num2 = 2
  387. assert test_state.dirty_vars == {"num1", "num2"}
  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. # The dirty vars should be reset.
  439. assert test_state.dirty_vars == set()
  440. assert child_state.dirty_vars == set()
  441. # The dirty substates should be reset.
  442. assert test_state.dirty_substates == set()
  443. @pytest.mark.asyncio
  444. async def test_process_event_simple(test_state):
  445. """Test processing an event.
  446. Args:
  447. test_state: A state.
  448. """
  449. assert test_state.num1 == 0
  450. event = Event(token="t", name="set_num1", payload={"value": 69})
  451. update = await test_state._process(event)
  452. # The event should update the value.
  453. assert test_state.num1 == 69
  454. # The delta should contain the changes, including computed vars.
  455. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  456. assert update.events == []
  457. @pytest.mark.asyncio
  458. async def test_process_event_substate(test_state, child_state, grandchild_state):
  459. """Test processing an event on a substate.
  460. Args:
  461. test_state: A state.
  462. child_state: A child state.
  463. grandchild_state: A grandchild state.
  464. """
  465. # Events should bubble down to the substate.
  466. assert child_state.value == ""
  467. assert child_state.count == 23
  468. event = Event(
  469. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  470. )
  471. update = await test_state._process(event)
  472. assert child_state.value == "HI"
  473. assert child_state.count == 24
  474. assert update.delta == {
  475. "test_state.child_state": {"value": "HI", "count": 24},
  476. }
  477. test_state.clean()
  478. # Test with the granchild state.
  479. assert grandchild_state.value2 == ""
  480. event = Event(
  481. token="t",
  482. name="child_state.grandchild_state.set_value2",
  483. payload={"value": "new"},
  484. )
  485. update = await test_state._process(event)
  486. assert grandchild_state.value2 == "new"
  487. assert update.delta == {
  488. "test_state.child_state.grandchild_state": {"value2": "new"},
  489. }
  490. def test_format_event_handler():
  491. """Test formatting an event handler."""
  492. assert (
  493. format.format_event_handler(TestState.do_something) == "test_state.do_something" # type: ignore
  494. )
  495. assert (
  496. format.format_event_handler(ChildState.change_both) # type: ignore
  497. == "test_state.child_state.change_both"
  498. )
  499. assert (
  500. format.format_event_handler(GrandchildState.do_nothing) # type: ignore
  501. == "test_state.child_state.grandchild_state.do_nothing"
  502. )
  503. def test_get_token(test_state):
  504. assert test_state.get_token() == ""
  505. token = "b181904c-3953-4a79-dc18-ae9518c22f05"
  506. test_state.router_data = {RouteVar.CLIENT_TOKEN: token}
  507. assert test_state.get_token() == token
  508. def test_get_sid(test_state):
  509. """Test getting session id.
  510. Args:
  511. test_state: A state.
  512. """
  513. assert test_state.get_sid() == ""
  514. sid = "9fpxSzPb9aFMb4wFAAAH"
  515. test_state.router_data = {RouteVar.SESSION_ID: sid}
  516. assert test_state.get_sid() == sid
  517. def test_get_headers(test_state):
  518. """Test getting client headers.
  519. Args:
  520. test_state: A state.
  521. """
  522. assert test_state.get_headers() == {}
  523. headers = {"host": "localhost:8000", "connection": "keep-alive"}
  524. test_state.router_data = {RouteVar.HEADERS: headers}
  525. assert test_state.get_headers() == headers
  526. def test_get_client_ip(test_state):
  527. """Test getting client IP.
  528. Args:
  529. test_state: A state.
  530. """
  531. assert test_state.get_client_ip() == ""
  532. client_ip = "127.0.0.1"
  533. test_state.router_data = {RouteVar.CLIENT_IP: client_ip}
  534. assert test_state.get_client_ip() == client_ip
  535. def test_get_current_page(test_state):
  536. assert test_state.get_current_page() == ""
  537. route = "mypage/subpage"
  538. test_state.router_data = {RouteVar.PATH: route}
  539. assert test_state.get_current_page() == route
  540. def test_get_query_params(test_state):
  541. assert test_state.get_query_params() == {}
  542. params = {"p1": "a", "p2": "b"}
  543. test_state.router_data = {RouteVar.QUERY: params}
  544. assert test_state.get_query_params() == params
  545. def test_add_var(test_state):
  546. test_state.add_var("dynamic_int", int, 42)
  547. assert test_state.dynamic_int == 42
  548. test_state.add_var("dynamic_list", List[int], [5, 10])
  549. assert test_state.dynamic_list == [5, 10]
  550. assert test_state.dynamic_list == [5, 10]
  551. # how to test that one?
  552. # test_state.dynamic_list.append(15)
  553. # assert test_state.dynamic_list == [5, 10, 15]
  554. test_state.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  555. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  556. assert test_state.dynamic_dict == {"k1": 5, "k2": 10}
  557. class InterdependentState(State):
  558. """A state with 3 vars and 3 computed vars.
  559. x: a variable that no computed var depends on
  560. v1: a varable that one computed var directly depeneds on
  561. _v2: a backend variable that one computed var directly depends on
  562. v1x2: a computed var that depends on v1
  563. v2x2: a computed var that depends on backend var _v2
  564. v1x2x2: a computed var that depends on computed var v1x2
  565. """
  566. x: int = 0
  567. v1: int = 0
  568. _v2: int = 1
  569. @ComputedVar
  570. def v1x2(self) -> int:
  571. """depends on var v1.
  572. Returns:
  573. Var v1 multiplied by 2
  574. """
  575. return self.v1 * 2
  576. @ComputedVar
  577. def v2x2(self) -> int:
  578. """depends on backend var _v2.
  579. Returns:
  580. backend var _v2 multiplied by 2
  581. """
  582. return self._v2 * 2
  583. @ComputedVar
  584. def v1x2x2(self) -> int:
  585. """depends on ComputedVar v1x2.
  586. Returns:
  587. ComputedVar v1x2 multiplied by 2
  588. """
  589. return self.v1x2 * 2
  590. @pytest.fixture
  591. def interdependent_state() -> State:
  592. """A state with varying dependency between vars.
  593. Returns:
  594. instance of InterdependentState
  595. """
  596. s = InterdependentState()
  597. s.dict() # prime initial relationships by accessing all ComputedVars
  598. return s
  599. def test_not_dirty_computed_var_from_var(interdependent_state):
  600. """Set Var that no ComputedVar depends on, expect no recalculation.
  601. Args:
  602. interdependent_state: A state with varying Var dependencies.
  603. """
  604. interdependent_state.x = 5
  605. assert interdependent_state.get_delta() == {
  606. interdependent_state.get_full_name(): {"x": 5},
  607. }
  608. def test_dirty_computed_var_from_var(interdependent_state):
  609. """Set Var that ComputedVar depends on, expect recalculation.
  610. The other ComputedVar depends on the changed ComputedVar and should also be
  611. recalculated. No other ComputedVars should be recalculated.
  612. Args:
  613. interdependent_state: A state with varying Var dependencies.
  614. """
  615. interdependent_state.v1 = 1
  616. assert interdependent_state.get_delta() == {
  617. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  618. }
  619. def test_dirty_computed_var_from_backend_var(interdependent_state):
  620. """Set backend var that ComputedVar depends on, expect recalculation.
  621. Args:
  622. interdependent_state: A state with varying Var dependencies.
  623. """
  624. interdependent_state._v2 = 2
  625. assert interdependent_state.get_delta() == {
  626. interdependent_state.get_full_name(): {"v2x2": 4},
  627. }