test_state.py 67 KB

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