1
0

test_state.py 46 KB

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