test_state.py 44 KB

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