test_state.py 80 KB

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