test_state.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143
  1. from __future__ import annotations
  2. import asyncio
  3. import copy
  4. import datetime
  5. import functools
  6. import json
  7. import os
  8. import sys
  9. from typing import Dict, Generator, List
  10. from unittest.mock import AsyncMock, Mock
  11. import pytest
  12. from plotly.graph_objects import Figure
  13. import reflex as rx
  14. from reflex.base import Base
  15. from reflex.constants import CompileVars, RouteVar, SocketEvent
  16. from reflex.event import Event, EventHandler
  17. from reflex.state import (
  18. ImmutableStateError,
  19. LockExpiredError,
  20. MutableProxy,
  21. State,
  22. StateManager,
  23. StateManagerMemory,
  24. StateManagerRedis,
  25. StateProxy,
  26. StateUpdate,
  27. )
  28. from reflex.utils import prerequisites
  29. from reflex.utils.format import json_dumps
  30. from reflex.vars import BaseVar, ComputedVar
  31. from .states import GenState
  32. CI = bool(os.environ.get("CI", False))
  33. LOCK_EXPIRATION = 2000 if CI else 100
  34. LOCK_EXPIRE_SLEEP = 2.5 if CI else 0.2
  35. class Object(Base):
  36. """A test object fixture."""
  37. prop1: int = 42
  38. prop2: str = "hello"
  39. class TestState(State):
  40. """A test state."""
  41. # Set this class as not test one
  42. __test__ = False
  43. num1: int
  44. num2: float = 3.14
  45. key: str
  46. map_key: str = "a"
  47. array: List[float] = [1, 2, 3.14]
  48. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  49. obj: Object = Object()
  50. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  51. fig: Figure = Figure()
  52. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  53. @ComputedVar
  54. def sum(self) -> float:
  55. """Dynamically sum the numbers.
  56. Returns:
  57. The sum of the numbers.
  58. """
  59. return self.num1 + self.num2
  60. @ComputedVar
  61. def upper(self) -> str:
  62. """Uppercase the key.
  63. Returns:
  64. The uppercased key.
  65. """
  66. return self.key.upper()
  67. def do_something(self):
  68. """Do something."""
  69. pass
  70. class ChildState(TestState):
  71. """A child state fixture."""
  72. value: str
  73. count: int = 23
  74. def change_both(self, value: str, count: int):
  75. """Change both the value and count.
  76. Args:
  77. value: The new value.
  78. count: The new count.
  79. """
  80. self.value = value.upper()
  81. self.count = count * 2
  82. class ChildState2(TestState):
  83. """A child state fixture."""
  84. value: str
  85. class GrandchildState(ChildState):
  86. """A grandchild state fixture."""
  87. value2: str
  88. def do_nothing(self):
  89. """Do something."""
  90. pass
  91. class DateTimeState(State):
  92. """A State with some datetime fields."""
  93. d: datetime.date = datetime.date.fromisoformat("1989-11-09")
  94. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  95. t: datetime.time = datetime.time.fromisoformat("18:53:00+01:00")
  96. td: datetime.timedelta = datetime.timedelta(days=11, minutes=11)
  97. @pytest.fixture
  98. def test_state() -> TestState:
  99. """A state.
  100. Returns:
  101. A test state.
  102. """
  103. return TestState() # type: ignore
  104. @pytest.fixture
  105. def child_state(test_state) -> ChildState:
  106. """A child state.
  107. Args:
  108. test_state: A test state.
  109. Returns:
  110. A test child state.
  111. """
  112. child_state = test_state.get_substate(["child_state"])
  113. assert child_state is not None
  114. return child_state
  115. @pytest.fixture
  116. def child_state2(test_state) -> ChildState2:
  117. """A second child state.
  118. Args:
  119. test_state: A test state.
  120. Returns:
  121. A second test child state.
  122. """
  123. child_state2 = test_state.get_substate(["child_state2"])
  124. assert child_state2 is not None
  125. return child_state2
  126. @pytest.fixture
  127. def grandchild_state(child_state) -> GrandchildState:
  128. """A state.
  129. Args:
  130. child_state: A child state.
  131. Returns:
  132. A test state.
  133. """
  134. grandchild_state = child_state.get_substate(["grandchild_state"])
  135. assert grandchild_state is not None
  136. return grandchild_state
  137. def test_base_class_vars(test_state):
  138. """Test that the class vars are set correctly.
  139. Args:
  140. test_state: A state.
  141. """
  142. fields = test_state.get_fields()
  143. cls = type(test_state)
  144. for field in fields:
  145. if field in test_state.get_skip_vars():
  146. continue
  147. prop = getattr(cls, field)
  148. assert isinstance(prop, BaseVar)
  149. assert prop.name == field
  150. assert cls.num1.type_ == int
  151. assert cls.num2.type_ == float
  152. assert cls.key.type_ == str
  153. def test_computed_class_var(test_state):
  154. """Test that the class computed vars are set correctly.
  155. Args:
  156. test_state: A state.
  157. """
  158. cls = type(test_state)
  159. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  160. assert ("sum", float) in vars
  161. assert ("upper", str) in vars
  162. def test_class_vars(test_state):
  163. """Test that the class vars are set correctly.
  164. Args:
  165. test_state: A state.
  166. """
  167. cls = type(test_state)
  168. assert set(cls.vars.keys()) == {
  169. CompileVars.IS_HYDRATED, # added by hydrate_middleware to all State
  170. "num1",
  171. "num2",
  172. "key",
  173. "map_key",
  174. "array",
  175. "mapping",
  176. "obj",
  177. "complex",
  178. "sum",
  179. "upper",
  180. "fig",
  181. "dt",
  182. }
  183. def test_event_handlers(test_state):
  184. """Test that event handler is set correctly.
  185. Args:
  186. test_state: A state.
  187. """
  188. expected = {
  189. "do_something",
  190. "set_array",
  191. "set_complex",
  192. "set_fig",
  193. "set_key",
  194. "set_mapping",
  195. "set_num1",
  196. "set_num2",
  197. "set_obj",
  198. }
  199. cls = type(test_state)
  200. assert set(cls.event_handlers.keys()).intersection(expected) == expected
  201. def test_default_value(test_state):
  202. """Test that the default value of a var is correct.
  203. Args:
  204. test_state: A state.
  205. """
  206. assert test_state.num1 == 0
  207. assert test_state.num2 == 3.14
  208. assert test_state.key == ""
  209. assert test_state.sum == 3.14
  210. assert test_state.upper == ""
  211. def test_computed_vars(test_state):
  212. """Test that the computed var is computed correctly.
  213. Args:
  214. test_state: A state.
  215. """
  216. test_state.num1 = 1
  217. test_state.num2 = 4
  218. assert test_state.sum == 5
  219. test_state.key = "hello world"
  220. assert test_state.upper == "HELLO WORLD"
  221. def test_dict(test_state):
  222. """Test that the dict representation of a state is correct.
  223. Args:
  224. test_state: A state.
  225. """
  226. substates = {"child_state", "child_state2"}
  227. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  228. assert (
  229. set(test_state.dict(include_computed=False).keys())
  230. == set(test_state.base_vars) | substates
  231. )
  232. def test_default_setters(test_state):
  233. """Test that we can set default values.
  234. Args:
  235. test_state: A state.
  236. """
  237. for prop_name in test_state.base_vars:
  238. # Each base var should have a default setter.
  239. assert hasattr(test_state, f"set_{prop_name}")
  240. def test_class_indexing_with_vars():
  241. """Test that we can index into a state var with another var."""
  242. prop = TestState.array[TestState.num1]
  243. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  244. prop = TestState.mapping["a"][TestState.num1]
  245. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  246. prop = TestState.mapping[TestState.map_key]
  247. assert str(prop) == "{test_state.mapping[test_state.map_key]}"
  248. def test_class_attributes():
  249. """Test that we can get class attributes."""
  250. prop = TestState.obj.prop1
  251. assert str(prop) == "{test_state.obj.prop1}"
  252. prop = TestState.complex[1].prop1
  253. assert str(prop) == "{test_state.complex[1].prop1}"
  254. def test_get_parent_state():
  255. """Test getting the parent state."""
  256. assert TestState.get_parent_state() is None
  257. assert ChildState.get_parent_state() == TestState
  258. assert ChildState2.get_parent_state() == TestState
  259. assert GrandchildState.get_parent_state() == ChildState
  260. def test_get_substates():
  261. """Test getting the substates."""
  262. assert TestState.get_substates() == {ChildState, ChildState2}
  263. assert ChildState.get_substates() == {GrandchildState}
  264. assert ChildState2.get_substates() == set()
  265. assert GrandchildState.get_substates() == set()
  266. def test_get_name():
  267. """Test getting the name of a state."""
  268. assert TestState.get_name() == "test_state"
  269. assert ChildState.get_name() == "child_state"
  270. assert ChildState2.get_name() == "child_state2"
  271. assert GrandchildState.get_name() == "grandchild_state"
  272. def test_get_full_name():
  273. """Test getting the full name."""
  274. assert TestState.get_full_name() == "test_state"
  275. assert ChildState.get_full_name() == "test_state.child_state"
  276. assert ChildState2.get_full_name() == "test_state.child_state2"
  277. assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
  278. def test_get_class_substate():
  279. """Test getting the substate of a class."""
  280. assert TestState.get_class_substate(("child_state",)) == ChildState
  281. assert TestState.get_class_substate(("child_state2",)) == ChildState2
  282. assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
  283. assert (
  284. TestState.get_class_substate(("child_state", "grandchild_state"))
  285. == GrandchildState
  286. )
  287. with pytest.raises(ValueError):
  288. TestState.get_class_substate(("invalid_child",))
  289. with pytest.raises(ValueError):
  290. TestState.get_class_substate(
  291. (
  292. "child_state",
  293. "invalid_child",
  294. )
  295. )
  296. def test_get_class_var():
  297. """Test getting the var of a class."""
  298. assert TestState.get_class_var(("num1",)).equals(TestState.num1)
  299. assert TestState.get_class_var(("num2",)).equals(TestState.num2)
  300. assert ChildState.get_class_var(("value",)).equals(ChildState.value)
  301. assert GrandchildState.get_class_var(("value2",)).equals(GrandchildState.value2)
  302. assert TestState.get_class_var(("child_state", "value")).equals(ChildState.value)
  303. assert TestState.get_class_var(
  304. ("child_state", "grandchild_state", "value2")
  305. ).equals(
  306. GrandchildState.value2,
  307. )
  308. assert ChildState.get_class_var(("grandchild_state", "value2")).equals(
  309. GrandchildState.value2,
  310. )
  311. with pytest.raises(ValueError):
  312. TestState.get_class_var(("invalid_var",))
  313. with pytest.raises(ValueError):
  314. TestState.get_class_var(
  315. (
  316. "child_state",
  317. "invalid_var",
  318. )
  319. )
  320. def test_set_class_var():
  321. """Test setting the var of a class."""
  322. with pytest.raises(AttributeError):
  323. TestState.num3 # type: ignore
  324. TestState._set_var(BaseVar(name="num3", type_=int).set_state(TestState))
  325. var = TestState.num3 # type: ignore
  326. assert var.name == "num3"
  327. assert var.type_ == int
  328. assert var.state == TestState.get_full_name()
  329. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  330. """Test setting the parent and substates.
  331. Args:
  332. test_state: A state.
  333. child_state: A child state.
  334. grandchild_state: A grandchild state.
  335. """
  336. assert len(test_state.substates) == 2
  337. assert set(test_state.substates) == {"child_state", "child_state2"}
  338. assert child_state.parent_state == test_state
  339. assert len(child_state.substates) == 1
  340. assert set(child_state.substates) == {"grandchild_state"}
  341. assert grandchild_state.parent_state == child_state
  342. assert len(grandchild_state.substates) == 0
  343. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  344. """Test getting the attribute of a state.
  345. Args:
  346. test_state: A state.
  347. child_state: A child state.
  348. child_state2: A child state.
  349. grandchild_state: A grandchild state.
  350. """
  351. assert test_state.num1 == 0
  352. assert child_state.value == ""
  353. assert child_state2.value == ""
  354. assert child_state.count == 23
  355. assert grandchild_state.value2 == ""
  356. with pytest.raises(AttributeError):
  357. test_state.invalid
  358. with pytest.raises(AttributeError):
  359. test_state.child_state.invalid
  360. with pytest.raises(AttributeError):
  361. test_state.child_state.grandchild_state.invalid
  362. def test_set_child_attribute(test_state, child_state, grandchild_state):
  363. """Test setting the attribute of a state.
  364. Args:
  365. test_state: A state.
  366. child_state: A child state.
  367. grandchild_state: A grandchild state.
  368. """
  369. test_state.num1 = 10
  370. assert test_state.num1 == 10
  371. assert child_state.num1 == 10
  372. assert grandchild_state.num1 == 10
  373. grandchild_state.num1 = 5
  374. assert test_state.num1 == 5
  375. assert child_state.num1 == 5
  376. assert grandchild_state.num1 == 5
  377. child_state.value = "test"
  378. assert child_state.value == "test"
  379. assert grandchild_state.value == "test"
  380. grandchild_state.value = "test2"
  381. assert child_state.value == "test2"
  382. assert grandchild_state.value == "test2"
  383. grandchild_state.value2 = "test3"
  384. assert grandchild_state.value2 == "test3"
  385. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  386. """Test getting the substate of a state.
  387. Args:
  388. test_state: A state.
  389. child_state: A child state.
  390. child_state2: A child state.
  391. grandchild_state: A grandchild state.
  392. """
  393. assert test_state.get_substate(("child_state",)) == child_state
  394. assert test_state.get_substate(("child_state2",)) == child_state2
  395. assert (
  396. test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
  397. )
  398. assert child_state.get_substate(("grandchild_state",)) == grandchild_state
  399. with pytest.raises(ValueError):
  400. test_state.get_substate(("invalid",))
  401. with pytest.raises(ValueError):
  402. test_state.get_substate(("child_state", "invalid"))
  403. with pytest.raises(ValueError):
  404. test_state.get_substate(("child_state", "grandchild_state", "invalid"))
  405. def test_set_dirty_var(test_state):
  406. """Test changing state vars marks the value as dirty.
  407. Args:
  408. test_state: A state.
  409. """
  410. # Initially there should be no dirty vars.
  411. assert test_state.dirty_vars == set()
  412. # Setting a var should mark it as dirty.
  413. test_state.num1 = 1
  414. assert test_state.dirty_vars == {"num1", "sum"}
  415. # Setting another var should mark it as dirty.
  416. test_state.num2 = 2
  417. assert test_state.dirty_vars == {"num1", "num2", "sum"}
  418. # Cleaning the state should remove all dirty vars.
  419. test_state._clean()
  420. assert test_state.dirty_vars == set()
  421. def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
  422. """Test changing substate vars marks the value as dirty.
  423. Args:
  424. test_state: A state.
  425. child_state: A child state.
  426. child_state2: A child state.
  427. grandchild_state: A grandchild state.
  428. """
  429. # Initially there should be no dirty vars.
  430. assert test_state.dirty_vars == set()
  431. assert child_state.dirty_vars == set()
  432. assert child_state2.dirty_vars == set()
  433. assert grandchild_state.dirty_vars == set()
  434. # Setting a var should mark it as dirty.
  435. child_state.value = "test"
  436. assert child_state.dirty_vars == {"value"}
  437. assert test_state.dirty_substates == {"child_state"}
  438. assert child_state.dirty_substates == set()
  439. # Cleaning the parent state should remove the dirty substate.
  440. test_state._clean()
  441. assert test_state.dirty_substates == set()
  442. assert child_state.dirty_vars == set()
  443. # Setting a var on the grandchild should bubble up.
  444. grandchild_state.value2 = "test2"
  445. assert child_state.dirty_substates == {"grandchild_state"}
  446. assert test_state.dirty_substates == {"child_state"}
  447. # Cleaning the middle state should keep the parent state dirty.
  448. child_state._clean()
  449. assert test_state.dirty_substates == {"child_state"}
  450. assert child_state.dirty_substates == set()
  451. assert grandchild_state.dirty_vars == set()
  452. def test_reset(test_state, child_state):
  453. """Test resetting the state.
  454. Args:
  455. test_state: A state.
  456. child_state: A child state.
  457. """
  458. # Set some values.
  459. test_state.num1 = 1
  460. test_state.num2 = 2
  461. child_state.value = "test"
  462. # Reset the state.
  463. test_state.reset()
  464. # The values should be reset.
  465. assert test_state.num1 == 0
  466. assert test_state.num2 == 3.14
  467. assert child_state.value == ""
  468. expected_dirty_vars = {
  469. "num1",
  470. "num2",
  471. "obj",
  472. "upper",
  473. "complex",
  474. "is_hydrated",
  475. "fig",
  476. "key",
  477. "sum",
  478. "array",
  479. "map_key",
  480. "mapping",
  481. "dt",
  482. }
  483. # The dirty vars should be reset.
  484. assert test_state.dirty_vars == expected_dirty_vars
  485. assert child_state.dirty_vars == {"count", "value"}
  486. # The dirty substates should be reset.
  487. assert test_state.dirty_substates == {"child_state", "child_state2"}
  488. @pytest.mark.asyncio
  489. async def test_process_event_simple(test_state):
  490. """Test processing an event.
  491. Args:
  492. test_state: A state.
  493. """
  494. assert test_state.num1 == 0
  495. event = Event(token="t", name="set_num1", payload={"value": 69})
  496. update = await test_state._process(event).__anext__()
  497. # The event should update the value.
  498. assert test_state.num1 == 69
  499. # The delta should contain the changes, including computed vars.
  500. # assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  501. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14, "upper": ""}}
  502. assert update.events == []
  503. @pytest.mark.asyncio
  504. async def test_process_event_substate(test_state, child_state, grandchild_state):
  505. """Test processing an event on a substate.
  506. Args:
  507. test_state: A state.
  508. child_state: A child state.
  509. grandchild_state: A grandchild state.
  510. """
  511. # Events should bubble down to the substate.
  512. assert child_state.value == ""
  513. assert child_state.count == 23
  514. event = Event(
  515. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  516. )
  517. update = await test_state._process(event).__anext__()
  518. assert child_state.value == "HI"
  519. assert child_state.count == 24
  520. assert update.delta == {
  521. "test_state": {"sum": 3.14, "upper": ""},
  522. "test_state.child_state": {"value": "HI", "count": 24},
  523. }
  524. test_state._clean()
  525. # Test with the granchild state.
  526. assert grandchild_state.value2 == ""
  527. event = Event(
  528. token="t",
  529. name="child_state.grandchild_state.set_value2",
  530. payload={"value": "new"},
  531. )
  532. update = await test_state._process(event).__anext__()
  533. assert grandchild_state.value2 == "new"
  534. assert update.delta == {
  535. "test_state": {"sum": 3.14, "upper": ""},
  536. "test_state.child_state.grandchild_state": {"value2": "new"},
  537. }
  538. @pytest.mark.asyncio
  539. async def test_process_event_generator():
  540. """Test event handlers that generate multiple updates."""
  541. gen_state = GenState() # type: ignore
  542. event = Event(
  543. token="t",
  544. name="go",
  545. payload={"c": 5},
  546. )
  547. gen = gen_state._process(event)
  548. count = 0
  549. async for update in gen:
  550. count += 1
  551. if count == 6:
  552. assert update.delta == {}
  553. assert update.final
  554. else:
  555. assert gen_state.value == count
  556. assert update.delta == {
  557. "gen_state": {"value": count},
  558. }
  559. assert not update.final
  560. assert count == 6
  561. def test_get_token(test_state, mocker, router_data):
  562. """Test that the token obtained from the router_data is correct.
  563. Args:
  564. test_state: The test state.
  565. mocker: Pytest Mocker object.
  566. router_data: The router data fixture.
  567. """
  568. mocker.patch.object(test_state, "router_data", router_data)
  569. assert test_state.get_token() == "b181904c-3953-4a79-dc18-ae9518c22f05"
  570. def test_get_sid(test_state, mocker, router_data):
  571. """Test getting session id.
  572. Args:
  573. test_state: A state.
  574. mocker: Pytest Mocker object.
  575. router_data: The router data fixture.
  576. """
  577. mocker.patch.object(test_state, "router_data", router_data)
  578. assert test_state.get_sid() == "9fpxSzPb9aFMb4wFAAAH"
  579. def test_get_headers(test_state, mocker, router_data, router_data_headers):
  580. """Test getting client headers.
  581. Args:
  582. test_state: A state.
  583. mocker: Pytest Mocker object.
  584. router_data: The router data fixture.
  585. router_data_headers: The expected headers.
  586. """
  587. mocker.patch.object(test_state, "router_data", router_data)
  588. assert test_state.get_headers() == router_data_headers
  589. def test_get_client_ip(test_state, mocker, router_data):
  590. """Test getting client IP.
  591. Args:
  592. test_state: A state.
  593. mocker: Pytest Mocker object.
  594. router_data: The router data fixture.
  595. """
  596. mocker.patch.object(test_state, "router_data", router_data)
  597. assert test_state.get_client_ip() == "127.0.0.1"
  598. def test_get_cookies(test_state, mocker, router_data):
  599. """Test getting client cookies.
  600. Args:
  601. test_state: A state.
  602. mocker: Pytest Mocker object.
  603. router_data: The router data fixture.
  604. """
  605. mocker.patch.object(test_state, "router_data", router_data)
  606. assert test_state.get_cookies() == {
  607. "csrftoken": "mocktoken",
  608. "name": "reflex",
  609. "list_cookies": ["some", "random", "cookies"],
  610. "dict_cookies": {"name": "reflex"},
  611. "val": True,
  612. }
  613. def test_get_current_page(test_state):
  614. assert test_state.get_current_page() == ""
  615. route = "mypage/subpage"
  616. test_state.router_data = {RouteVar.PATH: route}
  617. assert test_state.get_current_page() == route
  618. def test_get_query_params(test_state):
  619. assert test_state.get_query_params() == {}
  620. params = {"p1": "a", "p2": "b"}
  621. test_state.router_data = {RouteVar.QUERY: params}
  622. assert test_state.get_query_params() == params
  623. def test_add_var():
  624. class DynamicState(State):
  625. pass
  626. ds1 = DynamicState()
  627. assert "dynamic_int" not in ds1.__dict__
  628. assert not hasattr(ds1, "dynamic_int")
  629. ds1.add_var("dynamic_int", int, 42)
  630. # Existing instances get the BaseVar
  631. assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # type: ignore
  632. # New instances get an actual value with the default
  633. assert DynamicState().dynamic_int == 42
  634. ds1.add_var("dynamic_list", List[int], [5, 10])
  635. assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # type: ignore
  636. ds2 = DynamicState()
  637. assert ds2.dynamic_list == [5, 10]
  638. ds2.dynamic_list.append(15)
  639. assert ds2.dynamic_list == [5, 10, 15]
  640. assert DynamicState().dynamic_list == [5, 10]
  641. ds1.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  642. assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  643. assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  644. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  645. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  646. def test_add_var_default_handlers(test_state):
  647. test_state.add_var("rand_int", int, 10)
  648. assert "set_rand_int" in test_state.event_handlers
  649. assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
  650. class InterdependentState(State):
  651. """A state with 3 vars and 3 computed vars.
  652. x: a variable that no computed var depends on
  653. v1: a varable that one computed var directly depeneds on
  654. _v2: a backend variable that one computed var directly depends on
  655. v1x2: a computed var that depends on v1
  656. v2x2: a computed var that depends on backend var _v2
  657. v1x2x2: a computed var that depends on computed var v1x2
  658. """
  659. x: int = 0
  660. v1: int = 0
  661. _v2: int = 1
  662. @rx.cached_var
  663. def v1x2(self) -> int:
  664. """Depends on var v1.
  665. Returns:
  666. Var v1 multiplied by 2
  667. """
  668. return self.v1 * 2
  669. @rx.cached_var
  670. def v2x2(self) -> int:
  671. """Depends on backend var _v2.
  672. Returns:
  673. backend var _v2 multiplied by 2
  674. """
  675. return self._v2 * 2
  676. @rx.cached_var
  677. def v1x2x2(self) -> int:
  678. """Depends on ComputedVar v1x2.
  679. Returns:
  680. ComputedVar v1x2 multiplied by 2
  681. """
  682. return self.v1x2 * 2
  683. @pytest.fixture
  684. def interdependent_state() -> State:
  685. """A state with varying dependency between vars.
  686. Returns:
  687. instance of InterdependentState
  688. """
  689. s = InterdependentState()
  690. s.dict() # prime initial relationships by accessing all ComputedVars
  691. return s
  692. def test_not_dirty_computed_var_from_var(interdependent_state):
  693. """Set Var that no ComputedVar depends on, expect no recalculation.
  694. Args:
  695. interdependent_state: A state with varying Var dependencies.
  696. """
  697. interdependent_state.x = 5
  698. assert interdependent_state.get_delta() == {
  699. interdependent_state.get_full_name(): {"x": 5},
  700. }
  701. def test_dirty_computed_var_from_var(interdependent_state):
  702. """Set Var that ComputedVar depends on, expect recalculation.
  703. The other ComputedVar depends on the changed ComputedVar and should also be
  704. recalculated. No other ComputedVars should be recalculated.
  705. Args:
  706. interdependent_state: A state with varying Var dependencies.
  707. """
  708. interdependent_state.v1 = 1
  709. assert interdependent_state.get_delta() == {
  710. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  711. }
  712. def test_dirty_computed_var_from_backend_var(interdependent_state):
  713. """Set backend var that ComputedVar depends on, expect recalculation.
  714. Args:
  715. interdependent_state: A state with varying Var dependencies.
  716. """
  717. interdependent_state._v2 = 2
  718. assert interdependent_state.get_delta() == {
  719. interdependent_state.get_full_name(): {"v2x2": 4},
  720. }
  721. def test_per_state_backend_var(interdependent_state):
  722. """Set backend var on one instance, expect no affect in other instances.
  723. Args:
  724. interdependent_state: A state with varying Var dependencies.
  725. """
  726. s2 = InterdependentState()
  727. assert s2._v2 == interdependent_state._v2
  728. interdependent_state._v2 = 2
  729. assert s2._v2 != interdependent_state._v2
  730. s3 = InterdependentState()
  731. assert s3._v2 != interdependent_state._v2
  732. # both s2 and s3 should still have the default value
  733. assert s2._v2 == s3._v2
  734. # changing s2._v2 should not affect others
  735. s2._v2 = 4
  736. assert s2._v2 != interdependent_state._v2
  737. assert s2._v2 != s3._v2
  738. def test_child_state():
  739. """Test that the child state computed vars can reference parent state vars."""
  740. class MainState(State):
  741. v: int = 2
  742. class ChildState(MainState):
  743. @ComputedVar
  744. def rendered_var(self):
  745. return self.v
  746. ms = MainState()
  747. cs = ms.substates[ChildState.get_name()]
  748. assert ms.v == 2
  749. assert cs.v == 2
  750. assert cs.rendered_var == 2
  751. def test_conditional_computed_vars():
  752. """Test that computed vars can have conditionals."""
  753. class MainState(State):
  754. flag: bool = False
  755. t1: str = "a"
  756. t2: str = "b"
  757. @ComputedVar
  758. def rendered_var(self) -> str:
  759. if self.flag:
  760. return self.t1
  761. return self.t2
  762. ms = MainState()
  763. # Initially there are no dirty computed vars.
  764. assert ms._dirty_computed_vars(from_vars={"flag"}) == {"rendered_var"}
  765. assert ms._dirty_computed_vars(from_vars={"t2"}) == {"rendered_var"}
  766. assert ms._dirty_computed_vars(from_vars={"t1"}) == {"rendered_var"}
  767. assert ms.computed_vars["rendered_var"].deps(objclass=MainState) == {
  768. "flag",
  769. "t1",
  770. "t2",
  771. }
  772. def test_event_handlers_convert_to_fns(test_state, child_state):
  773. """Test that when the state is initialized, event handlers are converted to fns.
  774. Args:
  775. test_state: A state with event handlers.
  776. child_state: A child state with event handlers.
  777. """
  778. # The class instances should be event handlers.
  779. assert isinstance(TestState.do_something, EventHandler)
  780. assert isinstance(ChildState.change_both, EventHandler)
  781. # The object instances should be fns.
  782. test_state.do_something()
  783. child_state.change_both(value="goose", count=9)
  784. assert child_state.value == "GOOSE"
  785. assert child_state.count == 18
  786. def test_event_handlers_call_other_handlers():
  787. """Test that event handlers can call other event handlers."""
  788. class MainState(State):
  789. v: int = 0
  790. def set_v(self, v: int):
  791. self.v = v
  792. def set_v2(self, v: int):
  793. self.set_v(v)
  794. class SubState(MainState):
  795. def set_v3(self, v: int):
  796. self.set_v2(v)
  797. ms = MainState()
  798. ms.set_v2(1)
  799. assert ms.v == 1
  800. # ensure handler can be called from substate
  801. ms.substates[SubState.get_name()].set_v3(2)
  802. assert ms.v == 2
  803. def test_computed_var_cached():
  804. """Test that a ComputedVar doesn't recalculate when accessed."""
  805. comp_v_calls = 0
  806. class ComputedState(State):
  807. v: int = 0
  808. @rx.cached_var
  809. def comp_v(self) -> int:
  810. nonlocal comp_v_calls
  811. comp_v_calls += 1
  812. return self.v
  813. cs = ComputedState()
  814. assert cs.dict()["v"] == 0
  815. assert comp_v_calls == 1
  816. assert cs.dict()["comp_v"] == 0
  817. assert comp_v_calls == 1
  818. assert cs.comp_v == 0
  819. assert comp_v_calls == 1
  820. cs.v = 1
  821. assert comp_v_calls == 1
  822. assert cs.comp_v == 1
  823. assert comp_v_calls == 2
  824. def test_computed_var_cached_depends_on_non_cached():
  825. """Test that a cached_var is recalculated if it depends on non-cached ComputedVar."""
  826. class ComputedState(State):
  827. v: int = 0
  828. @rx.var
  829. def no_cache_v(self) -> int:
  830. return self.v
  831. @rx.cached_var
  832. def dep_v(self) -> int:
  833. return self.no_cache_v
  834. @rx.cached_var
  835. def comp_v(self) -> int:
  836. return self.v
  837. cs = ComputedState()
  838. assert cs.dirty_vars == set()
  839. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  840. cs._clean()
  841. assert cs.dirty_vars == set()
  842. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  843. cs._clean()
  844. assert cs.dirty_vars == set()
  845. cs.v = 1
  846. assert cs.dirty_vars == {"v", "comp_v", "dep_v", "no_cache_v"}
  847. assert cs.get_delta() == {
  848. cs.get_name(): {"v": 1, "no_cache_v": 1, "dep_v": 1, "comp_v": 1}
  849. }
  850. cs._clean()
  851. assert cs.dirty_vars == set()
  852. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  853. cs._clean()
  854. assert cs.dirty_vars == set()
  855. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  856. cs._clean()
  857. assert cs.dirty_vars == set()
  858. def test_computed_var_depends_on_parent_non_cached():
  859. """Child state cached_var that depends on parent state un cached var is always recalculated."""
  860. counter = 0
  861. class ParentState(State):
  862. @rx.var
  863. def no_cache_v(self) -> int:
  864. nonlocal counter
  865. counter += 1
  866. return counter
  867. class ChildState(ParentState):
  868. @rx.cached_var
  869. def dep_v(self) -> int:
  870. return self.no_cache_v
  871. ps = ParentState()
  872. cs = ps.substates[ChildState.get_name()]
  873. assert ps.dirty_vars == set()
  874. assert cs.dirty_vars == set()
  875. assert ps.dict() == {
  876. cs.get_name(): {"dep_v": 2},
  877. "no_cache_v": 1,
  878. CompileVars.IS_HYDRATED: False,
  879. }
  880. assert ps.dict() == {
  881. cs.get_name(): {"dep_v": 4},
  882. "no_cache_v": 3,
  883. CompileVars.IS_HYDRATED: False,
  884. }
  885. assert ps.dict() == {
  886. cs.get_name(): {"dep_v": 6},
  887. "no_cache_v": 5,
  888. CompileVars.IS_HYDRATED: False,
  889. }
  890. assert counter == 6
  891. @pytest.mark.parametrize("use_partial", [True, False])
  892. def test_cached_var_depends_on_event_handler(use_partial: bool):
  893. """A cached_var that calls an event handler calculates deps correctly.
  894. Args:
  895. use_partial: if true, replace the EventHandler with functools.partial
  896. """
  897. counter = 0
  898. class HandlerState(State):
  899. x: int = 42
  900. def handler(self):
  901. self.x = self.x + 1
  902. @rx.cached_var
  903. def cached_x_side_effect(self) -> int:
  904. self.handler()
  905. nonlocal counter
  906. counter += 1
  907. return counter
  908. if use_partial:
  909. HandlerState.handler = functools.partial(HandlerState.handler.fn)
  910. assert isinstance(HandlerState.handler, functools.partial)
  911. else:
  912. assert isinstance(HandlerState.handler, EventHandler)
  913. s = HandlerState()
  914. assert "cached_x_side_effect" in s.computed_var_dependencies["x"]
  915. assert s.cached_x_side_effect == 1
  916. assert s.x == 43
  917. s.handler()
  918. assert s.cached_x_side_effect == 2
  919. assert s.x == 45
  920. def test_computed_var_dependencies():
  921. """Test that a ComputedVar correctly tracks its dependencies."""
  922. class ComputedState(State):
  923. v: int = 0
  924. w: int = 0
  925. x: int = 0
  926. y: List[int] = [1, 2, 3]
  927. _z: List[int] = [1, 2, 3]
  928. @rx.cached_var
  929. def comp_v(self) -> int:
  930. """Direct access.
  931. Returns:
  932. The value of self.v.
  933. """
  934. return self.v
  935. @rx.cached_var
  936. def comp_w(self):
  937. """Nested lambda.
  938. Returns:
  939. A lambda that returns the value of self.w.
  940. """
  941. return lambda: self.w
  942. @rx.cached_var
  943. def comp_x(self):
  944. """Nested function.
  945. Returns:
  946. A function that returns the value of self.x.
  947. """
  948. def _():
  949. return self.x
  950. return _
  951. @rx.cached_var
  952. def comp_y(self) -> List[int]:
  953. """Comprehension iterating over attribute.
  954. Returns:
  955. A list of the values of self.y.
  956. """
  957. return [round(y) for y in self.y]
  958. @rx.cached_var
  959. def comp_z(self) -> List[bool]:
  960. """Comprehension accesses attribute.
  961. Returns:
  962. A list of whether the values 0-4 are in self._z.
  963. """
  964. return [z in self._z for z in range(5)]
  965. cs = ComputedState()
  966. assert cs.computed_var_dependencies["v"] == {"comp_v"}
  967. assert cs.computed_var_dependencies["w"] == {"comp_w"}
  968. assert cs.computed_var_dependencies["x"] == {"comp_x"}
  969. assert cs.computed_var_dependencies["y"] == {"comp_y"}
  970. assert cs.computed_var_dependencies["_z"] == {"comp_z"}
  971. def test_backend_method():
  972. """A method with leading underscore should be callable from event handler."""
  973. class BackendMethodState(State):
  974. def _be_method(self):
  975. return True
  976. def handler(self):
  977. assert self._be_method()
  978. bms = BackendMethodState()
  979. bms.handler()
  980. assert bms._be_method()
  981. def test_setattr_of_mutable_types(mutable_state):
  982. """Test that mutable types are converted to corresponding Reflex wrappers.
  983. Args:
  984. mutable_state: A test state.
  985. """
  986. array = mutable_state.array
  987. hashmap = mutable_state.hashmap
  988. test_set = mutable_state.test_set
  989. assert isinstance(array, MutableProxy)
  990. assert isinstance(array, list)
  991. assert isinstance(array[1], MutableProxy)
  992. assert isinstance(array[1], list)
  993. assert isinstance(array[2], MutableProxy)
  994. assert isinstance(array[2], dict)
  995. assert isinstance(hashmap, MutableProxy)
  996. assert isinstance(hashmap, dict)
  997. assert isinstance(hashmap["key"], MutableProxy)
  998. assert isinstance(hashmap["key"], list)
  999. assert isinstance(hashmap["third_key"], MutableProxy)
  1000. assert isinstance(hashmap["third_key"], dict)
  1001. assert isinstance(test_set, MutableProxy)
  1002. assert isinstance(test_set, set)
  1003. assert isinstance(mutable_state.custom, MutableProxy)
  1004. assert isinstance(mutable_state.custom.array, MutableProxy)
  1005. assert isinstance(mutable_state.custom.array, list)
  1006. assert isinstance(mutable_state.custom.hashmap, MutableProxy)
  1007. assert isinstance(mutable_state.custom.hashmap, dict)
  1008. assert isinstance(mutable_state.custom.test_set, MutableProxy)
  1009. assert isinstance(mutable_state.custom.test_set, set)
  1010. assert isinstance(mutable_state.custom.custom, MutableProxy)
  1011. mutable_state.reassign_mutables()
  1012. array = mutable_state.array
  1013. hashmap = mutable_state.hashmap
  1014. test_set = mutable_state.test_set
  1015. assert isinstance(array, MutableProxy)
  1016. assert isinstance(array, list)
  1017. assert isinstance(array[1], MutableProxy)
  1018. assert isinstance(array[1], list)
  1019. assert isinstance(array[2], MutableProxy)
  1020. assert isinstance(array[2], dict)
  1021. assert isinstance(hashmap, MutableProxy)
  1022. assert isinstance(hashmap, dict)
  1023. assert isinstance(hashmap["mod_key"], MutableProxy)
  1024. assert isinstance(hashmap["mod_key"], list)
  1025. assert isinstance(hashmap["mod_third_key"], MutableProxy)
  1026. assert isinstance(hashmap["mod_third_key"], dict)
  1027. assert isinstance(test_set, MutableProxy)
  1028. assert isinstance(test_set, set)
  1029. def test_error_on_state_method_shadow():
  1030. """Test that an error is thrown when an event handler shadows a state method."""
  1031. with pytest.raises(NameError) as err:
  1032. class InvalidTest(rx.State):
  1033. def reset(self):
  1034. pass
  1035. assert (
  1036. err.value.args[0]
  1037. == f"The event handler name `reset` shadows a builtin State method; use a different name instead"
  1038. )
  1039. def test_state_with_invalid_yield():
  1040. """Test that an error is thrown when a state yields an invalid value."""
  1041. class StateWithInvalidYield(rx.State):
  1042. """A state that yields an invalid value."""
  1043. def invalid_handler(self):
  1044. """Invalid handler.
  1045. Yields:
  1046. an invalid value.
  1047. """
  1048. yield 1
  1049. invalid_state = StateWithInvalidYield()
  1050. with pytest.raises(TypeError) as err:
  1051. invalid_state._check_valid(
  1052. invalid_state.event_handlers["invalid_handler"],
  1053. rx.event.Event(token="fake_token", name="invalid_handler"),
  1054. )
  1055. assert (
  1056. "must only return/yield: None, Events or other EventHandlers"
  1057. in err.value.args[0]
  1058. )
  1059. @pytest.fixture(scope="function", params=["in_process", "redis"])
  1060. def state_manager(request) -> Generator[StateManager, None, None]:
  1061. """Instance of state manager parametrized for redis and in-process.
  1062. Args:
  1063. request: pytest request object.
  1064. Yields:
  1065. A state manager instance
  1066. """
  1067. state_manager = StateManager.create(state=TestState)
  1068. if request.param == "redis":
  1069. if not isinstance(state_manager, StateManagerRedis):
  1070. pytest.skip("Test requires redis")
  1071. else:
  1072. # explicitly NOT using redis
  1073. state_manager = StateManagerMemory(state=TestState)
  1074. assert not state_manager._states_locks
  1075. yield state_manager
  1076. if isinstance(state_manager, StateManagerRedis):
  1077. asyncio.get_event_loop().run_until_complete(state_manager.redis.close())
  1078. @pytest.mark.asyncio
  1079. async def test_state_manager_modify_state(state_manager: StateManager, token: str):
  1080. """Test that the state manager can modify a state exclusively.
  1081. Args:
  1082. state_manager: A state manager instance.
  1083. token: A token.
  1084. """
  1085. async with state_manager.modify_state(token):
  1086. if isinstance(state_manager, StateManagerRedis):
  1087. assert await state_manager.redis.get(f"{token}_lock")
  1088. elif isinstance(state_manager, StateManagerMemory):
  1089. assert token in state_manager._states_locks
  1090. assert state_manager._states_locks[token].locked()
  1091. # lock should be dropped after exiting the context
  1092. if isinstance(state_manager, StateManagerRedis):
  1093. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1094. elif isinstance(state_manager, StateManagerMemory):
  1095. assert not state_manager._states_locks[token].locked()
  1096. # separate instances should NOT share locks
  1097. sm2 = StateManagerMemory(state=TestState)
  1098. assert sm2._state_manager_lock is state_manager._state_manager_lock
  1099. assert not sm2._states_locks
  1100. if state_manager._states_locks:
  1101. assert sm2._states_locks != state_manager._states_locks
  1102. @pytest.mark.asyncio
  1103. async def test_state_manager_contend(state_manager: StateManager, token: str):
  1104. """Multiple coroutines attempting to access the same state.
  1105. Args:
  1106. state_manager: A state manager instance.
  1107. token: A token.
  1108. """
  1109. n_coroutines = 10
  1110. exp_num1 = 10
  1111. async with state_manager.modify_state(token) as state:
  1112. state.num1 = 0
  1113. async def _coro():
  1114. async with state_manager.modify_state(token) as state:
  1115. await asyncio.sleep(0.01)
  1116. state.num1 += 1
  1117. tasks = [asyncio.create_task(_coro()) for _ in range(n_coroutines)]
  1118. for f in asyncio.as_completed(tasks):
  1119. await f
  1120. assert (await state_manager.get_state(token)).num1 == exp_num1
  1121. if isinstance(state_manager, StateManagerRedis):
  1122. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1123. elif isinstance(state_manager, StateManagerMemory):
  1124. assert token in state_manager._states_locks
  1125. assert not state_manager._states_locks[token].locked()
  1126. @pytest.fixture(scope="function")
  1127. def state_manager_redis() -> Generator[StateManager, None, None]:
  1128. """Instance of state manager for redis only.
  1129. Yields:
  1130. A state manager instance
  1131. """
  1132. state_manager = StateManager.create(TestState)
  1133. if not isinstance(state_manager, StateManagerRedis):
  1134. pytest.skip("Test requires redis")
  1135. yield state_manager
  1136. asyncio.get_event_loop().run_until_complete(state_manager.redis.close())
  1137. @pytest.mark.asyncio
  1138. async def test_state_manager_lock_expire(state_manager_redis: StateManager, token: str):
  1139. """Test that the state manager lock expires and raises exception exiting context.
  1140. Args:
  1141. state_manager_redis: A state manager instance.
  1142. token: A token.
  1143. """
  1144. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1145. async with state_manager_redis.modify_state(token):
  1146. await asyncio.sleep(0.01)
  1147. with pytest.raises(LockExpiredError):
  1148. async with state_manager_redis.modify_state(token):
  1149. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1150. @pytest.mark.asyncio
  1151. async def test_state_manager_lock_expire_contend(
  1152. state_manager_redis: StateManager, token: str
  1153. ):
  1154. """Test that the state manager lock expires and queued waiters proceed.
  1155. Args:
  1156. state_manager_redis: A state manager instance.
  1157. token: A token.
  1158. """
  1159. exp_num1 = 4252
  1160. unexp_num1 = 666
  1161. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1162. order = []
  1163. async def _coro_blocker():
  1164. async with state_manager_redis.modify_state(token) as state:
  1165. order.append("blocker")
  1166. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1167. state.num1 = unexp_num1
  1168. async def _coro_waiter():
  1169. while "blocker" not in order:
  1170. await asyncio.sleep(0.005)
  1171. async with state_manager_redis.modify_state(token) as state:
  1172. order.append("waiter")
  1173. assert state.num1 != unexp_num1
  1174. state.num1 = exp_num1
  1175. tasks = [
  1176. asyncio.create_task(_coro_blocker()),
  1177. asyncio.create_task(_coro_waiter()),
  1178. ]
  1179. with pytest.raises(LockExpiredError):
  1180. await tasks[0]
  1181. await tasks[1]
  1182. assert order == ["blocker", "waiter"]
  1183. assert (await state_manager_redis.get_state(token)).num1 == exp_num1
  1184. @pytest.fixture(scope="function")
  1185. def mock_app(monkeypatch, app: rx.App, state_manager: StateManager) -> rx.App:
  1186. """Mock app fixture.
  1187. Args:
  1188. monkeypatch: Pytest monkeypatch object.
  1189. app: An app.
  1190. state_manager: A state manager.
  1191. Returns:
  1192. The app, after mocking out prerequisites.get_app()
  1193. """
  1194. app_module = Mock()
  1195. setattr(app_module, CompileVars.APP, app)
  1196. app.state = TestState
  1197. app.state_manager = state_manager
  1198. assert app.event_namespace is not None
  1199. app.event_namespace.emit = AsyncMock()
  1200. monkeypatch.setattr(prerequisites, "get_app", lambda: app_module)
  1201. return app
  1202. @pytest.mark.asyncio
  1203. async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
  1204. """Test that the state proxy works.
  1205. Args:
  1206. grandchild_state: A grandchild state.
  1207. mock_app: An app that will be returned by `get_app()`
  1208. """
  1209. child_state = grandchild_state.parent_state
  1210. assert child_state is not None
  1211. parent_state = child_state.parent_state
  1212. assert parent_state is not None
  1213. if isinstance(mock_app.state_manager, StateManagerMemory):
  1214. mock_app.state_manager.states[parent_state.get_token()] = parent_state
  1215. sp = StateProxy(grandchild_state)
  1216. assert sp.__wrapped__ == grandchild_state
  1217. assert sp._self_substate_path == grandchild_state.get_full_name().split(".")
  1218. assert sp._self_app is mock_app
  1219. assert not sp._self_mutable
  1220. assert sp._self_actx is None
  1221. # cannot use normal contextmanager protocol
  1222. with pytest.raises(TypeError), sp:
  1223. pass
  1224. with pytest.raises(ImmutableStateError):
  1225. # cannot directly modify state proxy outside of async context
  1226. sp.value2 = 16
  1227. async with sp:
  1228. assert sp._self_actx is not None
  1229. assert sp._self_mutable # proxy is mutable inside context
  1230. if isinstance(mock_app.state_manager, StateManagerMemory):
  1231. # For in-process store, only one instance of the state exists
  1232. assert sp.__wrapped__ is grandchild_state
  1233. else:
  1234. # When redis is used, a new+updated instance is assigned to the proxy
  1235. assert sp.__wrapped__ is not grandchild_state
  1236. sp.value2 = 42
  1237. assert not sp._self_mutable # proxy is not mutable after exiting context
  1238. assert sp._self_actx is None
  1239. assert sp.value2 == 42
  1240. # Get the state from the state manager directly and check that the value is updated
  1241. gotten_state = await mock_app.state_manager.get_state(grandchild_state.get_token())
  1242. if isinstance(mock_app.state_manager, StateManagerMemory):
  1243. # For in-process store, only one instance of the state exists
  1244. assert gotten_state is parent_state
  1245. else:
  1246. assert gotten_state is not parent_state
  1247. gotten_grandchild_state = gotten_state.get_substate(sp._self_substate_path)
  1248. assert gotten_grandchild_state is not None
  1249. assert gotten_grandchild_state.value2 == 42
  1250. # ensure state update was emitted
  1251. assert mock_app.event_namespace is not None
  1252. mock_app.event_namespace.emit.assert_called_once()
  1253. mcall = mock_app.event_namespace.emit.mock_calls[0]
  1254. assert mcall.args[0] == str(SocketEvent.EVENT)
  1255. assert json.loads(mcall.args[1]) == StateUpdate(
  1256. delta={
  1257. parent_state.get_full_name(): {
  1258. "upper": "",
  1259. "sum": 3.14,
  1260. },
  1261. grandchild_state.get_full_name(): {
  1262. "value2": 42,
  1263. },
  1264. }
  1265. )
  1266. assert mcall.kwargs["to"] == grandchild_state.get_sid()
  1267. class BackgroundTaskState(State):
  1268. """A state with a background task."""
  1269. order: List[str] = []
  1270. dict_list: Dict[str, List[int]] = {"foo": [1, 2, 3]}
  1271. @rx.background
  1272. async def background_task(self):
  1273. """A background task that updates the state."""
  1274. async with self:
  1275. assert not self.order
  1276. self.order.append("background_task:start")
  1277. assert isinstance(self, StateProxy)
  1278. with pytest.raises(ImmutableStateError):
  1279. self.order.append("bad idea")
  1280. with pytest.raises(ImmutableStateError):
  1281. # Even nested access to mutables raises an exception.
  1282. self.dict_list["foo"].append(42)
  1283. with pytest.raises(ImmutableStateError):
  1284. # Direct calling another handler that modifies state raises an exception.
  1285. self.other()
  1286. with pytest.raises(ImmutableStateError):
  1287. # Calling other methods that modify state raises an exception.
  1288. self._private_method()
  1289. # wait for some other event to happen
  1290. while len(self.order) == 1:
  1291. await asyncio.sleep(0.01)
  1292. async with self:
  1293. pass # update proxy instance
  1294. async with self:
  1295. # Methods on ImmutableMutableProxy should return their wrapped return value.
  1296. assert self.dict_list.pop("foo") is not None
  1297. self.order.append("background_task:stop")
  1298. self.other() # direct calling event handlers works in context
  1299. self._private_method()
  1300. @rx.background
  1301. async def background_task_reset(self):
  1302. """A background task that resets the state."""
  1303. with pytest.raises(ImmutableStateError):
  1304. # Resetting the state should be explicitly blocked.
  1305. self.reset()
  1306. async with self:
  1307. self.order.append("foo")
  1308. self.reset()
  1309. assert not self.order
  1310. async with self:
  1311. self.order.append("reset")
  1312. @rx.background
  1313. async def background_task_generator(self):
  1314. """A background task generator that does nothing.
  1315. Yields:
  1316. None
  1317. """
  1318. yield
  1319. def other(self):
  1320. """Some other event that updates the state."""
  1321. self.order.append("other")
  1322. def _private_method(self):
  1323. """Some private method that updates the state."""
  1324. self.order.append("private")
  1325. async def bad_chain1(self):
  1326. """Test that a background task cannot be chained."""
  1327. await self.background_task()
  1328. async def bad_chain2(self):
  1329. """Test that a background task generator cannot be chained."""
  1330. async for _foo in self.background_task_generator():
  1331. pass
  1332. @pytest.mark.asyncio
  1333. async def test_background_task_no_block(mock_app: rx.App, token: str):
  1334. """Test that a background task does not block other events.
  1335. Args:
  1336. mock_app: An app that will be returned by `get_app()`
  1337. token: A token.
  1338. """
  1339. router_data = {"query": {}}
  1340. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1341. async for update in rx.app.process( # type: ignore
  1342. mock_app,
  1343. Event(
  1344. token=token,
  1345. name=f"{BackgroundTaskState.get_name()}.background_task",
  1346. router_data=router_data,
  1347. payload={},
  1348. ),
  1349. sid="",
  1350. headers={},
  1351. client_ip="",
  1352. ):
  1353. # background task returns empty update immediately
  1354. assert update == StateUpdate()
  1355. # wait for the coroutine to start
  1356. await asyncio.sleep(0.5 if CI else 0.1)
  1357. assert len(mock_app.background_tasks) == 1
  1358. # Process another normal event
  1359. async for update in rx.app.process( # type: ignore
  1360. mock_app,
  1361. Event(
  1362. token=token,
  1363. name=f"{BackgroundTaskState.get_name()}.other",
  1364. router_data=router_data,
  1365. payload={},
  1366. ),
  1367. sid="",
  1368. headers={},
  1369. client_ip="",
  1370. ):
  1371. # other task returns delta
  1372. assert update == StateUpdate(
  1373. delta={
  1374. BackgroundTaskState.get_name(): {
  1375. "order": [
  1376. "background_task:start",
  1377. "other",
  1378. ],
  1379. }
  1380. }
  1381. )
  1382. # Explicit wait for background tasks
  1383. for task in tuple(mock_app.background_tasks):
  1384. await task
  1385. assert not mock_app.background_tasks
  1386. assert (await mock_app.state_manager.get_state(token)).order == [
  1387. "background_task:start",
  1388. "other",
  1389. "background_task:stop",
  1390. "other",
  1391. "private",
  1392. ]
  1393. @pytest.mark.asyncio
  1394. async def test_background_task_reset(mock_app: rx.App, token: str):
  1395. """Test that a background task calling reset is protected by the state proxy.
  1396. Args:
  1397. mock_app: An app that will be returned by `get_app()`
  1398. token: A token.
  1399. """
  1400. router_data = {"query": {}}
  1401. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1402. async for update in rx.app.process( # type: ignore
  1403. mock_app,
  1404. Event(
  1405. token=token,
  1406. name=f"{BackgroundTaskState.get_name()}.background_task_reset",
  1407. router_data=router_data,
  1408. payload={},
  1409. ),
  1410. sid="",
  1411. headers={},
  1412. client_ip="",
  1413. ):
  1414. # background task returns empty update immediately
  1415. assert update == StateUpdate()
  1416. # Explicit wait for background tasks
  1417. for task in tuple(mock_app.background_tasks):
  1418. await task
  1419. assert not mock_app.background_tasks
  1420. assert (await mock_app.state_manager.get_state(token)).order == [
  1421. "reset",
  1422. ]
  1423. @pytest.mark.asyncio
  1424. async def test_background_task_no_chain():
  1425. """Test that a background task cannot be chained."""
  1426. bts = BackgroundTaskState()
  1427. with pytest.raises(RuntimeError):
  1428. await bts.bad_chain1()
  1429. with pytest.raises(RuntimeError):
  1430. await bts.bad_chain2()
  1431. def test_mutable_list(mutable_state):
  1432. """Test that mutable lists are tracked correctly.
  1433. Args:
  1434. mutable_state: A test state.
  1435. """
  1436. assert not mutable_state.dirty_vars
  1437. def assert_array_dirty():
  1438. assert mutable_state.dirty_vars == {"array"}
  1439. mutable_state._clean()
  1440. assert not mutable_state.dirty_vars
  1441. # Test all list operations
  1442. mutable_state.array.append(42)
  1443. assert_array_dirty()
  1444. mutable_state.array.extend([1, 2, 3])
  1445. assert_array_dirty()
  1446. mutable_state.array.insert(0, 0)
  1447. assert_array_dirty()
  1448. mutable_state.array.pop()
  1449. assert_array_dirty()
  1450. mutable_state.array.remove(42)
  1451. assert_array_dirty()
  1452. mutable_state.array.clear()
  1453. assert_array_dirty()
  1454. mutable_state.array += [1, 2, 3]
  1455. assert_array_dirty()
  1456. mutable_state.array.reverse()
  1457. assert_array_dirty()
  1458. mutable_state.array.sort()
  1459. assert_array_dirty()
  1460. mutable_state.array[0] = 666
  1461. assert_array_dirty()
  1462. del mutable_state.array[0]
  1463. assert_array_dirty()
  1464. # Test nested list operations
  1465. mutable_state.array[0] = [1, 2, 3]
  1466. assert_array_dirty()
  1467. mutable_state.array[0].append(4)
  1468. assert_array_dirty()
  1469. assert isinstance(mutable_state.array[0], MutableProxy)
  1470. # Test proxy returned from __iter__
  1471. mutable_state.array = [{}]
  1472. assert_array_dirty()
  1473. assert isinstance(mutable_state.array[0], MutableProxy)
  1474. for item in mutable_state.array:
  1475. assert isinstance(item, MutableProxy)
  1476. item["foo"] = "bar"
  1477. assert_array_dirty()
  1478. def test_mutable_dict(mutable_state):
  1479. """Test that mutable dicts are tracked correctly.
  1480. Args:
  1481. mutable_state: A test state.
  1482. """
  1483. assert not mutable_state.dirty_vars
  1484. def assert_hashmap_dirty():
  1485. assert mutable_state.dirty_vars == {"hashmap"}
  1486. mutable_state._clean()
  1487. assert not mutable_state.dirty_vars
  1488. # Test all dict operations
  1489. mutable_state.hashmap.update({"new_key": 43})
  1490. assert_hashmap_dirty()
  1491. assert mutable_state.hashmap.setdefault("another_key", 66) == "another_value"
  1492. assert_hashmap_dirty()
  1493. assert mutable_state.hashmap.setdefault("setdefault_key", 67) == 67
  1494. assert_hashmap_dirty()
  1495. assert mutable_state.hashmap.setdefault("setdefault_key", 68) == 67
  1496. assert_hashmap_dirty()
  1497. assert mutable_state.hashmap.pop("new_key") == 43
  1498. assert_hashmap_dirty()
  1499. mutable_state.hashmap.popitem()
  1500. assert_hashmap_dirty()
  1501. mutable_state.hashmap.clear()
  1502. assert_hashmap_dirty()
  1503. mutable_state.hashmap["new_key"] = 42
  1504. assert_hashmap_dirty()
  1505. del mutable_state.hashmap["new_key"]
  1506. assert_hashmap_dirty()
  1507. if sys.version_info >= (3, 9):
  1508. mutable_state.hashmap |= {"new_key": 44}
  1509. assert_hashmap_dirty()
  1510. # Test nested dict operations
  1511. mutable_state.hashmap["array"] = []
  1512. assert_hashmap_dirty()
  1513. mutable_state.hashmap["array"].append(1)
  1514. assert_hashmap_dirty()
  1515. mutable_state.hashmap["dict"] = {}
  1516. assert_hashmap_dirty()
  1517. mutable_state.hashmap["dict"]["key"] = 42
  1518. assert_hashmap_dirty()
  1519. mutable_state.hashmap["dict"]["dict"] = {}
  1520. assert_hashmap_dirty()
  1521. mutable_state.hashmap["dict"]["dict"]["key"] = 43
  1522. assert_hashmap_dirty()
  1523. # Test proxy returned from `setdefault` and `get`
  1524. mutable_value = mutable_state.hashmap.setdefault("setdefault_mutable_key", [])
  1525. assert_hashmap_dirty()
  1526. assert mutable_value == []
  1527. assert isinstance(mutable_value, MutableProxy)
  1528. mutable_value.append("foo")
  1529. assert_hashmap_dirty()
  1530. mutable_value_other_ref = mutable_state.hashmap.get("setdefault_mutable_key")
  1531. assert isinstance(mutable_value_other_ref, MutableProxy)
  1532. assert mutable_value is not mutable_value_other_ref
  1533. assert mutable_value == mutable_value_other_ref
  1534. assert not mutable_state.dirty_vars
  1535. mutable_value_other_ref.append("bar")
  1536. assert_hashmap_dirty()
  1537. # `pop` should NOT return a proxy, because the returned value is no longer in the dict
  1538. mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key")
  1539. assert not isinstance(mutable_value_third_ref, MutableProxy)
  1540. assert_hashmap_dirty()
  1541. mutable_value_third_ref.append("baz")
  1542. assert not mutable_state.dirty_vars
  1543. # Unfortunately previous refs still will mark the state dirty... nothing doing about that
  1544. assert mutable_value.pop()
  1545. assert_hashmap_dirty()
  1546. def test_mutable_set(mutable_state):
  1547. """Test that mutable sets are tracked correctly.
  1548. Args:
  1549. mutable_state: A test state.
  1550. """
  1551. assert not mutable_state.dirty_vars
  1552. def assert_set_dirty():
  1553. assert mutable_state.dirty_vars == {"test_set"}
  1554. mutable_state._clean()
  1555. assert not mutable_state.dirty_vars
  1556. # Test all set operations
  1557. mutable_state.test_set.add(42)
  1558. assert_set_dirty()
  1559. mutable_state.test_set.update([1, 2, 3])
  1560. assert_set_dirty()
  1561. mutable_state.test_set.remove(42)
  1562. assert_set_dirty()
  1563. mutable_state.test_set.discard(3)
  1564. assert_set_dirty()
  1565. mutable_state.test_set.pop()
  1566. assert_set_dirty()
  1567. mutable_state.test_set.intersection_update([1, 2, 3])
  1568. assert_set_dirty()
  1569. mutable_state.test_set.difference_update([99])
  1570. assert_set_dirty()
  1571. mutable_state.test_set.symmetric_difference_update([102, 99])
  1572. assert_set_dirty()
  1573. mutable_state.test_set |= {1, 2, 3}
  1574. assert_set_dirty()
  1575. mutable_state.test_set &= {2, 3, 4}
  1576. assert_set_dirty()
  1577. mutable_state.test_set -= {2}
  1578. assert_set_dirty()
  1579. mutable_state.test_set ^= {42}
  1580. assert_set_dirty()
  1581. mutable_state.test_set.clear()
  1582. assert_set_dirty()
  1583. def test_mutable_custom(mutable_state):
  1584. """Test that mutable custom types derived from Base are tracked correctly.
  1585. Args:
  1586. mutable_state: A test state.
  1587. """
  1588. assert not mutable_state.dirty_vars
  1589. def assert_custom_dirty():
  1590. assert mutable_state.dirty_vars == {"custom"}
  1591. mutable_state._clean()
  1592. assert not mutable_state.dirty_vars
  1593. mutable_state.custom.foo = "bar"
  1594. assert_custom_dirty()
  1595. mutable_state.custom.array.append(42)
  1596. assert_custom_dirty()
  1597. mutable_state.custom.hashmap["key"] = 68
  1598. assert_custom_dirty()
  1599. mutable_state.custom.test_set.add(42)
  1600. assert_custom_dirty()
  1601. mutable_state.custom.custom.bar = "baz"
  1602. assert_custom_dirty()
  1603. def test_mutable_backend(mutable_state):
  1604. """Test that mutable backend vars are tracked correctly.
  1605. Args:
  1606. mutable_state: A test state.
  1607. """
  1608. assert not mutable_state.dirty_vars
  1609. def assert_custom_dirty():
  1610. assert mutable_state.dirty_vars == {"_be_custom"}
  1611. mutable_state._clean()
  1612. assert not mutable_state.dirty_vars
  1613. mutable_state._be_custom.foo = "bar"
  1614. assert_custom_dirty()
  1615. mutable_state._be_custom.array.append(42)
  1616. assert_custom_dirty()
  1617. mutable_state._be_custom.hashmap["key"] = 68
  1618. assert_custom_dirty()
  1619. mutable_state._be_custom.test_set.add(42)
  1620. assert_custom_dirty()
  1621. mutable_state._be_custom.custom.bar = "baz"
  1622. assert_custom_dirty()
  1623. @pytest.mark.parametrize(
  1624. ("copy_func",),
  1625. [
  1626. (copy.copy,),
  1627. (copy.deepcopy,),
  1628. ],
  1629. )
  1630. def test_mutable_copy(mutable_state, copy_func):
  1631. """Test that mutable types are copied correctly.
  1632. Args:
  1633. mutable_state: A test state.
  1634. copy_func: A copy function.
  1635. """
  1636. ms_copy = copy_func(mutable_state)
  1637. assert ms_copy is not mutable_state
  1638. for attr in ("array", "hashmap", "test_set", "custom"):
  1639. assert getattr(ms_copy, attr) == getattr(mutable_state, attr)
  1640. assert getattr(ms_copy, attr) is not getattr(mutable_state, attr)
  1641. ms_copy.custom.array.append(42)
  1642. assert "custom" in ms_copy.dirty_vars
  1643. if copy_func is copy.copy:
  1644. assert "custom" in mutable_state.dirty_vars
  1645. else:
  1646. assert not mutable_state.dirty_vars
  1647. @pytest.mark.parametrize(
  1648. ("copy_func",),
  1649. [
  1650. (copy.copy,),
  1651. (copy.deepcopy,),
  1652. ],
  1653. )
  1654. def test_mutable_copy_vars(mutable_state, copy_func):
  1655. """Test that mutable types are copied correctly.
  1656. Args:
  1657. mutable_state: A test state.
  1658. copy_func: A copy function.
  1659. """
  1660. for attr in ("array", "hashmap", "test_set", "custom"):
  1661. var_orig = getattr(mutable_state, attr)
  1662. var_copy = copy_func(var_orig)
  1663. assert var_orig is not var_copy
  1664. assert var_orig == var_copy
  1665. # copied vars should never be proxies, as they by definition are no longer attached to the state.
  1666. assert not isinstance(var_copy, MutableProxy)
  1667. def test_duplicate_substate_class(duplicate_substate):
  1668. with pytest.raises(ValueError):
  1669. duplicate_substate()
  1670. class Foo(Base):
  1671. """A class containing a list of str."""
  1672. tags: List[str] = ["123", "456"]
  1673. def test_json_dumps_with_mutables():
  1674. """Test that json.dumps works with Base vars inside mutable types."""
  1675. class MutableContainsBase(State):
  1676. items: List[Foo] = [Foo()]
  1677. dict_val = MutableContainsBase().dict()
  1678. assert isinstance(dict_val["items"][0], dict)
  1679. val = json_dumps(dict_val)
  1680. assert val == '{"is_hydrated": false, "items": [{"tags": ["123", "456"]}]}'
  1681. def test_reset_with_mutables():
  1682. """Calling reset should always reset fields to a copy of the defaults."""
  1683. default = [[0, 0], [0, 1], [1, 1]]
  1684. copied_default = copy.deepcopy(default)
  1685. class MutableResetState(State):
  1686. items: List[List[int]] = default
  1687. instance = MutableResetState()
  1688. assert instance.items.__wrapped__ is not default # type: ignore
  1689. assert instance.items == default == copied_default
  1690. instance.items.append([3, 3])
  1691. assert instance.items != default
  1692. assert instance.items != copied_default
  1693. instance.reset()
  1694. assert instance.items.__wrapped__ is not default # type: ignore
  1695. assert instance.items == default == copied_default
  1696. instance.items.append([3, 3])
  1697. assert instance.items != default
  1698. assert instance.items != copied_default
  1699. instance.reset()
  1700. assert instance.items.__wrapped__ is not default # type: ignore
  1701. assert instance.items == default == copied_default
  1702. instance.items.append([3, 3])
  1703. assert instance.items != default
  1704. assert instance.items != copied_default