test_state.py 107 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634
  1. from __future__ import annotations
  2. import asyncio
  3. import copy
  4. import dataclasses
  5. import datetime
  6. import functools
  7. import json
  8. import os
  9. import sys
  10. import threading
  11. from textwrap import dedent
  12. from typing import (
  13. Any,
  14. AsyncGenerator,
  15. Callable,
  16. Dict,
  17. List,
  18. Optional,
  19. Set,
  20. Tuple,
  21. Union,
  22. )
  23. from unittest.mock import AsyncMock, Mock
  24. import pytest
  25. import pytest_asyncio
  26. from plotly.graph_objects import Figure
  27. from pydantic import BaseModel as BaseModelV2
  28. from pydantic.v1 import BaseModel as BaseModelV1
  29. import reflex as rx
  30. import reflex.config
  31. from reflex import constants
  32. from reflex.app import App
  33. from reflex.base import Base
  34. from reflex.components.sonner.toast import Toaster
  35. from reflex.constants import CompileVars, RouteVar, SocketEvent
  36. from reflex.event import Event, EventHandler
  37. from reflex.state import (
  38. BaseState,
  39. ImmutableStateError,
  40. LockExpiredError,
  41. MutableProxy,
  42. OnLoadInternalState,
  43. RouterData,
  44. State,
  45. StateManager,
  46. StateManagerDisk,
  47. StateManagerMemory,
  48. StateManagerRedis,
  49. StateProxy,
  50. StateUpdate,
  51. _substate_key,
  52. )
  53. from reflex.testing import chdir
  54. from reflex.utils import format, prerequisites, types
  55. from reflex.utils.exceptions import ReflexRuntimeError, SetUndefinedStateVarError
  56. from reflex.utils.format import json_dumps
  57. from reflex.vars.base import Var, computed_var
  58. from tests.units.states.mutation import MutableSQLAModel, MutableTestState
  59. from .states import GenState
  60. CI = bool(os.environ.get("CI", False))
  61. LOCK_EXPIRATION = 2000 if CI else 300
  62. LOCK_EXPIRE_SLEEP = 2.5 if CI else 0.4
  63. formatted_router = {
  64. "session": {"client_token": "", "client_ip": "", "session_id": ""},
  65. "headers": {
  66. "host": "",
  67. "origin": "",
  68. "upgrade": "",
  69. "connection": "",
  70. "cookie": "",
  71. "pragma": "",
  72. "cache_control": "",
  73. "user_agent": "",
  74. "sec_websocket_version": "",
  75. "sec_websocket_key": "",
  76. "sec_websocket_extensions": "",
  77. "accept_encoding": "",
  78. "accept_language": "",
  79. },
  80. "page": {
  81. "host": "",
  82. "path": "",
  83. "raw_path": "",
  84. "full_path": "",
  85. "full_raw_path": "",
  86. "params": {},
  87. },
  88. }
  89. class Object(Base):
  90. """A test object fixture."""
  91. prop1: int = 42
  92. prop2: str = "hello"
  93. class TestState(BaseState):
  94. """A test state."""
  95. # Set this class as not test one
  96. __test__ = False
  97. num1: int
  98. num2: float = 3.14
  99. key: str
  100. map_key: str = "a"
  101. array: List[float] = [1, 2, 3.14]
  102. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  103. obj: Object = Object()
  104. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  105. fig: Figure = Figure()
  106. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  107. _backend: int = 0
  108. asynctest: int = 0
  109. @computed_var
  110. def sum(self) -> float:
  111. """Dynamically sum the numbers.
  112. Returns:
  113. The sum of the numbers.
  114. """
  115. return self.num1 + self.num2
  116. @computed_var
  117. def upper(self) -> str:
  118. """Uppercase the key.
  119. Returns:
  120. The uppercased key.
  121. """
  122. return self.key.upper()
  123. def do_something(self):
  124. """Do something."""
  125. pass
  126. async def set_asynctest(self, value: int):
  127. """Set the asynctest value. Intentionally overwrite the default setter with an async one.
  128. Args:
  129. value: The new value.
  130. """
  131. self.asynctest = value
  132. class ChildState(TestState):
  133. """A child state fixture."""
  134. value: str
  135. count: int = 23
  136. def change_both(self, value: str, count: int):
  137. """Change both the value and count.
  138. Args:
  139. value: The new value.
  140. count: The new count.
  141. """
  142. self.value = value.upper()
  143. self.count = count * 2
  144. class ChildState2(TestState):
  145. """A child state fixture."""
  146. value: str
  147. class ChildState3(TestState):
  148. """A child state fixture."""
  149. value: str
  150. class GrandchildState(ChildState):
  151. """A grandchild state fixture."""
  152. value2: str
  153. def do_nothing(self):
  154. """Do something."""
  155. pass
  156. class GrandchildState2(ChildState2):
  157. """A grandchild state fixture."""
  158. @rx.var(cache=True)
  159. def cached(self) -> str:
  160. """A cached var.
  161. Returns:
  162. The value.
  163. """
  164. return self.value
  165. class GrandchildState3(ChildState3):
  166. """A great grandchild state fixture."""
  167. @rx.var
  168. def computed(self) -> str:
  169. """A computed var.
  170. Returns:
  171. The value.
  172. """
  173. return self.value
  174. class DateTimeState(BaseState):
  175. """A State with some datetime fields."""
  176. d: datetime.date = datetime.date.fromisoformat("1989-11-09")
  177. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  178. t: datetime.time = datetime.time.fromisoformat("18:53:00+01:00")
  179. td: datetime.timedelta = datetime.timedelta(days=11, minutes=11)
  180. @pytest.fixture
  181. def test_state() -> TestState:
  182. """A state.
  183. Returns:
  184. A test state.
  185. """
  186. return TestState() # type: ignore
  187. @pytest.fixture
  188. def child_state(test_state) -> ChildState:
  189. """A child state.
  190. Args:
  191. test_state: A test state.
  192. Returns:
  193. A test child state.
  194. """
  195. child_state = test_state.get_substate([ChildState.get_name()])
  196. assert child_state is not None
  197. return child_state
  198. @pytest.fixture
  199. def child_state2(test_state) -> ChildState2:
  200. """A second child state.
  201. Args:
  202. test_state: A test state.
  203. Returns:
  204. A second test child state.
  205. """
  206. child_state2 = test_state.get_substate([ChildState2.get_name()])
  207. assert child_state2 is not None
  208. return child_state2
  209. @pytest.fixture
  210. def grandchild_state(child_state) -> GrandchildState:
  211. """A state.
  212. Args:
  213. child_state: A child state.
  214. Returns:
  215. A test state.
  216. """
  217. grandchild_state = child_state.get_substate([GrandchildState.get_name()])
  218. assert grandchild_state is not None
  219. return grandchild_state
  220. def test_base_class_vars(test_state):
  221. """Test that the class vars are set correctly.
  222. Args:
  223. test_state: A state.
  224. """
  225. fields = test_state.get_fields()
  226. cls = type(test_state)
  227. for field in fields:
  228. if field in test_state.get_skip_vars():
  229. continue
  230. prop = getattr(cls, field)
  231. assert isinstance(prop, Var)
  232. assert prop._js_expr.split(".")[-1] == field
  233. assert cls.num1._var_type is int
  234. assert cls.num2._var_type is float
  235. assert cls.key._var_type is str
  236. def test_computed_class_var(test_state):
  237. """Test that the class computed vars are set correctly.
  238. Args:
  239. test_state: A state.
  240. """
  241. cls = type(test_state)
  242. vars = [(prop._js_expr, prop._var_type) for prop in cls.computed_vars.values()]
  243. assert ("sum", float) in vars
  244. assert ("upper", str) in vars
  245. def test_class_vars(test_state):
  246. """Test that the class vars are set correctly.
  247. Args:
  248. test_state: A state.
  249. """
  250. cls = type(test_state)
  251. assert cls.vars.keys() == {
  252. "router",
  253. "num1",
  254. "num2",
  255. "key",
  256. "map_key",
  257. "array",
  258. "mapping",
  259. "obj",
  260. "complex",
  261. "sum",
  262. "upper",
  263. "fig",
  264. "dt",
  265. "asynctest",
  266. }
  267. def test_event_handlers(test_state):
  268. """Test that event handler is set correctly.
  269. Args:
  270. test_state: A state.
  271. """
  272. expected_keys = (
  273. "do_something",
  274. "set_array",
  275. "set_complex",
  276. "set_fig",
  277. "set_key",
  278. "set_mapping",
  279. "set_num1",
  280. "set_num2",
  281. "set_obj",
  282. )
  283. cls = type(test_state)
  284. assert all(key in cls.event_handlers for key in expected_keys)
  285. def test_default_value(test_state):
  286. """Test that the default value of a var is correct.
  287. Args:
  288. test_state: A state.
  289. """
  290. assert test_state.num1 == 0
  291. assert test_state.num2 == 3.14
  292. assert test_state.key == ""
  293. assert test_state.sum == 3.14
  294. assert test_state.upper == ""
  295. def test_computed_vars(test_state):
  296. """Test that the computed var is computed correctly.
  297. Args:
  298. test_state: A state.
  299. """
  300. test_state.num1 = 1
  301. test_state.num2 = 4
  302. assert test_state.sum == 5
  303. test_state.key = "hello world"
  304. assert test_state.upper == "HELLO WORLD"
  305. def test_dict(test_state: TestState):
  306. """Test that the dict representation of a state is correct.
  307. Args:
  308. test_state: A state.
  309. """
  310. substates = {
  311. test_state.get_full_name(),
  312. ChildState.get_full_name(),
  313. GrandchildState.get_full_name(),
  314. ChildState2.get_full_name(),
  315. GrandchildState2.get_full_name(),
  316. ChildState3.get_full_name(),
  317. GrandchildState3.get_full_name(),
  318. }
  319. test_state_dict = test_state.dict()
  320. assert set(test_state_dict) == substates
  321. assert set(test_state_dict[test_state.get_name()]) == set(test_state.vars)
  322. assert set(test_state.dict(include_computed=False)[test_state.get_name()]) == set(
  323. test_state.base_vars
  324. )
  325. def test_default_setters(test_state):
  326. """Test that we can set default values.
  327. Args:
  328. test_state: A state.
  329. """
  330. for prop_name in test_state.base_vars:
  331. # Each base var should have a default setter.
  332. assert hasattr(test_state, f"set_{prop_name}")
  333. def test_class_indexing_with_vars():
  334. """Test that we can index into a state var with another var."""
  335. prop = TestState.array[TestState.num1]
  336. assert str(prop) == f"{TestState.get_name()}.array.at({TestState.get_name()}.num1)"
  337. prop = TestState.mapping["a"][TestState.num1]
  338. assert (
  339. str(prop)
  340. == f'{TestState.get_name()}.mapping["a"].at({TestState.get_name()}.num1)'
  341. )
  342. prop = TestState.mapping[TestState.map_key]
  343. assert (
  344. str(prop) == f"{TestState.get_name()}.mapping[{TestState.get_name()}.map_key]"
  345. )
  346. def test_class_attributes():
  347. """Test that we can get class attributes."""
  348. prop = TestState.obj.prop1
  349. assert str(prop) == f'{TestState.get_name()}.obj["prop1"]'
  350. prop = TestState.complex[1].prop1
  351. assert str(prop) == f'{TestState.get_name()}.complex[1]["prop1"]'
  352. def test_get_parent_state():
  353. """Test getting the parent state."""
  354. assert TestState.get_parent_state() is None
  355. assert ChildState.get_parent_state() == TestState
  356. assert ChildState2.get_parent_state() == TestState
  357. assert GrandchildState.get_parent_state() == ChildState
  358. def test_get_substates():
  359. """Test getting the substates."""
  360. assert TestState.get_substates() == {ChildState, ChildState2, ChildState3}
  361. assert ChildState.get_substates() == {GrandchildState}
  362. assert ChildState2.get_substates() == {GrandchildState2}
  363. assert GrandchildState.get_substates() == set()
  364. assert GrandchildState2.get_substates() == set()
  365. def test_get_name():
  366. """Test getting the name of a state."""
  367. assert TestState.get_name() == "tests___units___test_state____test_state"
  368. assert ChildState.get_name() == "tests___units___test_state____child_state"
  369. assert ChildState2.get_name() == "tests___units___test_state____child_state2"
  370. assert (
  371. GrandchildState.get_name() == "tests___units___test_state____grandchild_state"
  372. )
  373. def test_get_full_name():
  374. """Test getting the full name."""
  375. assert TestState.get_full_name() == "tests___units___test_state____test_state"
  376. assert (
  377. ChildState.get_full_name()
  378. == "tests___units___test_state____test_state.tests___units___test_state____child_state"
  379. )
  380. assert (
  381. ChildState2.get_full_name()
  382. == "tests___units___test_state____test_state.tests___units___test_state____child_state2"
  383. )
  384. assert (
  385. GrandchildState.get_full_name()
  386. == "tests___units___test_state____test_state.tests___units___test_state____child_state.tests___units___test_state____grandchild_state"
  387. )
  388. def test_get_class_substate():
  389. """Test getting the substate of a class."""
  390. assert TestState.get_class_substate((ChildState.get_name(),)) == ChildState
  391. assert TestState.get_class_substate((ChildState2.get_name(),)) == ChildState2
  392. assert (
  393. ChildState.get_class_substate((GrandchildState.get_name(),)) == GrandchildState
  394. )
  395. assert (
  396. TestState.get_class_substate(
  397. (ChildState.get_name(), GrandchildState.get_name())
  398. )
  399. == GrandchildState
  400. )
  401. with pytest.raises(ValueError):
  402. TestState.get_class_substate(("invalid_child",))
  403. with pytest.raises(ValueError):
  404. TestState.get_class_substate(
  405. (
  406. ChildState.get_name(),
  407. "invalid_child",
  408. )
  409. )
  410. def test_get_class_var():
  411. """Test getting the var of a class."""
  412. assert TestState.get_class_var(("num1",)).equals(TestState.num1)
  413. assert TestState.get_class_var(("num2",)).equals(TestState.num2)
  414. assert ChildState.get_class_var(("value",)).equals(ChildState.value)
  415. assert GrandchildState.get_class_var(("value2",)).equals(GrandchildState.value2)
  416. assert TestState.get_class_var((ChildState.get_name(), "value")).equals(
  417. ChildState.value
  418. )
  419. assert TestState.get_class_var(
  420. (ChildState.get_name(), GrandchildState.get_name(), "value2")
  421. ).equals(
  422. GrandchildState.value2,
  423. )
  424. assert ChildState.get_class_var((GrandchildState.get_name(), "value2")).equals(
  425. GrandchildState.value2,
  426. )
  427. with pytest.raises(ValueError):
  428. TestState.get_class_var(("invalid_var",))
  429. with pytest.raises(ValueError):
  430. TestState.get_class_var(
  431. (
  432. ChildState.get_name(),
  433. "invalid_var",
  434. )
  435. )
  436. def test_set_class_var():
  437. """Test setting the var of a class."""
  438. with pytest.raises(AttributeError):
  439. TestState.num3 # type: ignore
  440. TestState._set_var(Var(_js_expr="num3", _var_type=int)._var_set_state(TestState))
  441. var = TestState.num3 # type: ignore
  442. assert var._js_expr == TestState.get_full_name() + ".num3"
  443. assert var._var_type is int
  444. assert var._var_state == TestState.get_full_name()
  445. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  446. """Test setting the parent and substates.
  447. Args:
  448. test_state: A state.
  449. child_state: A child state.
  450. grandchild_state: A grandchild state.
  451. """
  452. assert len(test_state.substates) == 3
  453. assert set(test_state.substates) == {
  454. ChildState.get_name(),
  455. ChildState2.get_name(),
  456. ChildState3.get_name(),
  457. }
  458. assert child_state.parent_state == test_state
  459. assert len(child_state.substates) == 1
  460. assert set(child_state.substates) == {GrandchildState.get_name()}
  461. assert grandchild_state.parent_state == child_state
  462. assert len(grandchild_state.substates) == 0
  463. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  464. """Test getting the attribute of a state.
  465. Args:
  466. test_state: A state.
  467. child_state: A child state.
  468. child_state2: A child state.
  469. grandchild_state: A grandchild state.
  470. """
  471. assert test_state.num1 == 0
  472. assert child_state.value == ""
  473. assert child_state2.value == ""
  474. assert child_state.count == 23
  475. assert grandchild_state.value2 == ""
  476. with pytest.raises(AttributeError):
  477. test_state.invalid
  478. with pytest.raises(AttributeError):
  479. test_state.child_state.invalid
  480. with pytest.raises(AttributeError):
  481. test_state.child_state.grandchild_state.invalid
  482. def test_set_child_attribute(test_state, child_state, grandchild_state):
  483. """Test setting the attribute of a state.
  484. Args:
  485. test_state: A state.
  486. child_state: A child state.
  487. grandchild_state: A grandchild state.
  488. """
  489. test_state.num1 = 10
  490. assert test_state.num1 == 10
  491. assert child_state.num1 == 10
  492. assert grandchild_state.num1 == 10
  493. grandchild_state.num1 = 5
  494. assert test_state.num1 == 5
  495. assert child_state.num1 == 5
  496. assert grandchild_state.num1 == 5
  497. child_state.value = "test"
  498. assert child_state.value == "test"
  499. assert grandchild_state.value == "test"
  500. grandchild_state.value = "test2"
  501. assert child_state.value == "test2"
  502. assert grandchild_state.value == "test2"
  503. grandchild_state.value2 = "test3"
  504. assert grandchild_state.value2 == "test3"
  505. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  506. """Test getting the substate of a state.
  507. Args:
  508. test_state: A state.
  509. child_state: A child state.
  510. child_state2: A child state.
  511. grandchild_state: A grandchild state.
  512. """
  513. assert test_state.get_substate((ChildState.get_name(),)) == child_state
  514. assert test_state.get_substate((ChildState2.get_name(),)) == child_state2
  515. assert (
  516. test_state.get_substate((ChildState.get_name(), GrandchildState.get_name()))
  517. == grandchild_state
  518. )
  519. assert child_state.get_substate((GrandchildState.get_name(),)) == grandchild_state
  520. with pytest.raises(ValueError):
  521. test_state.get_substate(("invalid",))
  522. with pytest.raises(ValueError):
  523. test_state.get_substate((ChildState.get_name(), "invalid"))
  524. with pytest.raises(ValueError):
  525. test_state.get_substate(
  526. (ChildState.get_name(), GrandchildState.get_name(), "invalid")
  527. )
  528. def test_set_dirty_var(test_state):
  529. """Test changing state vars marks the value as dirty.
  530. Args:
  531. test_state: A state.
  532. """
  533. # Initially there should be no dirty vars.
  534. assert test_state.dirty_vars == set()
  535. # Setting a var should mark it as dirty.
  536. test_state.num1 = 1
  537. assert test_state.dirty_vars == {"num1", "sum"}
  538. # Setting another var should mark it as dirty.
  539. test_state.num2 = 2
  540. assert test_state.dirty_vars == {"num1", "num2", "sum"}
  541. # Cleaning the state should remove all dirty vars.
  542. test_state._clean()
  543. assert test_state.dirty_vars == set()
  544. def test_set_dirty_substate(
  545. test_state: TestState,
  546. child_state: ChildState,
  547. child_state2: ChildState2,
  548. grandchild_state: GrandchildState,
  549. ):
  550. """Test changing substate vars marks the value as dirty.
  551. Args:
  552. test_state: A state.
  553. child_state: A child state.
  554. child_state2: A child state.
  555. grandchild_state: A grandchild state.
  556. """
  557. # Initially there should be no dirty vars.
  558. assert test_state.dirty_vars == set()
  559. assert child_state.dirty_vars == set()
  560. assert child_state2.dirty_vars == set()
  561. assert grandchild_state.dirty_vars == set()
  562. # Setting a var should mark it as dirty.
  563. child_state.value = "test"
  564. assert child_state.dirty_vars == {"value"}
  565. assert test_state.dirty_substates == {ChildState.get_name()}
  566. assert child_state.dirty_substates == set()
  567. # Cleaning the parent state should remove the dirty substate.
  568. test_state._clean()
  569. assert test_state.dirty_substates == set()
  570. assert child_state.dirty_vars == set()
  571. # Setting a var on the grandchild should bubble up.
  572. grandchild_state.value2 = "test2"
  573. assert child_state.dirty_substates == {GrandchildState.get_name()}
  574. assert test_state.dirty_substates == {ChildState.get_name()}
  575. # Cleaning the middle state should keep the parent state dirty.
  576. child_state._clean()
  577. assert test_state.dirty_substates == {ChildState.get_name()}
  578. assert child_state.dirty_substates == set()
  579. assert grandchild_state.dirty_vars == set()
  580. def test_reset(test_state, child_state):
  581. """Test resetting the state.
  582. Args:
  583. test_state: A state.
  584. child_state: A child state.
  585. """
  586. # Set some values.
  587. test_state.num1 = 1
  588. test_state.num2 = 2
  589. test_state._backend = 3
  590. child_state.value = "test"
  591. # Reset the state.
  592. test_state.reset()
  593. # The values should be reset.
  594. assert test_state.num1 == 0
  595. assert test_state.num2 == 3.14
  596. assert test_state._backend == 0
  597. assert child_state.value == ""
  598. expected_dirty_vars = {
  599. "num1",
  600. "num2",
  601. "obj",
  602. "upper",
  603. "complex",
  604. "fig",
  605. "key",
  606. "sum",
  607. "array",
  608. "map_key",
  609. "mapping",
  610. "dt",
  611. "_backend",
  612. "asynctest",
  613. }
  614. # The dirty vars should be reset.
  615. assert test_state.dirty_vars == expected_dirty_vars
  616. assert child_state.dirty_vars == {"count", "value"}
  617. # The dirty substates should be reset.
  618. assert test_state.dirty_substates == {
  619. ChildState.get_name(),
  620. ChildState2.get_name(),
  621. ChildState3.get_name(),
  622. }
  623. @pytest.mark.asyncio
  624. async def test_process_event_simple(test_state):
  625. """Test processing an event.
  626. Args:
  627. test_state: A state.
  628. """
  629. assert test_state.num1 == 0
  630. event = Event(token="t", name="set_num1", payload={"value": 69})
  631. update = await test_state._process(event).__anext__()
  632. # The event should update the value.
  633. assert test_state.num1 == 69
  634. # The delta should contain the changes, including computed vars.
  635. # assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  636. assert update.delta == {
  637. TestState.get_full_name(): {"num1": 69, "sum": 72.14, "upper": ""},
  638. GrandchildState3.get_full_name(): {"computed": ""},
  639. }
  640. assert update.events == []
  641. @pytest.mark.asyncio
  642. async def test_process_event_substate(test_state, child_state, grandchild_state):
  643. """Test processing an event on a substate.
  644. Args:
  645. test_state: A state.
  646. child_state: A child state.
  647. grandchild_state: A grandchild state.
  648. """
  649. # Events should bubble down to the substate.
  650. assert child_state.value == ""
  651. assert child_state.count == 23
  652. event = Event(
  653. token="t",
  654. name=f"{ChildState.get_name()}.change_both",
  655. payload={"value": "hi", "count": 12},
  656. )
  657. update = await test_state._process(event).__anext__()
  658. assert child_state.value == "HI"
  659. assert child_state.count == 24
  660. assert update.delta == {
  661. TestState.get_full_name(): {"sum": 3.14, "upper": ""},
  662. ChildState.get_full_name(): {"value": "HI", "count": 24},
  663. GrandchildState3.get_full_name(): {"computed": ""},
  664. }
  665. test_state._clean()
  666. # Test with the granchild state.
  667. assert grandchild_state.value2 == ""
  668. event = Event(
  669. token="t",
  670. name=f"{GrandchildState.get_full_name()}.set_value2",
  671. payload={"value": "new"},
  672. )
  673. update = await test_state._process(event).__anext__()
  674. assert grandchild_state.value2 == "new"
  675. assert update.delta == {
  676. TestState.get_full_name(): {"sum": 3.14, "upper": ""},
  677. GrandchildState.get_full_name(): {"value2": "new"},
  678. GrandchildState3.get_full_name(): {"computed": ""},
  679. }
  680. @pytest.mark.asyncio
  681. async def test_process_event_generator():
  682. """Test event handlers that generate multiple updates."""
  683. gen_state = GenState() # type: ignore
  684. event = Event(
  685. token="t",
  686. name="go",
  687. payload={"c": 5},
  688. )
  689. gen = gen_state._process(event)
  690. count = 0
  691. async for update in gen:
  692. count += 1
  693. if count == 6:
  694. assert update.delta == {}
  695. assert update.final
  696. else:
  697. assert gen_state.value == count
  698. assert update.delta == {
  699. GenState.get_full_name(): {"value": count},
  700. }
  701. assert not update.final
  702. assert count == 6
  703. def test_get_client_token(test_state, router_data):
  704. """Test that the token obtained from the router_data is correct.
  705. Args:
  706. test_state: The test state.
  707. router_data: The router data fixture.
  708. """
  709. test_state.router = RouterData(router_data)
  710. assert (
  711. test_state.router.session.client_token == "b181904c-3953-4a79-dc18-ae9518c22f05"
  712. )
  713. def test_get_sid(test_state, router_data):
  714. """Test getting session id.
  715. Args:
  716. test_state: A state.
  717. router_data: The router data fixture.
  718. """
  719. test_state.router = RouterData(router_data)
  720. assert test_state.router.session.session_id == "9fpxSzPb9aFMb4wFAAAH"
  721. def test_get_headers(test_state, router_data, router_data_headers):
  722. """Test getting client headers.
  723. Args:
  724. test_state: A state.
  725. router_data: The router data fixture.
  726. router_data_headers: The expected headers.
  727. """
  728. print(router_data_headers)
  729. test_state.router = RouterData(router_data)
  730. print(test_state.router.headers)
  731. assert dataclasses.asdict(test_state.router.headers) == {
  732. format.to_snake_case(k): v for k, v in router_data_headers.items()
  733. }
  734. def test_get_client_ip(test_state, router_data):
  735. """Test getting client IP.
  736. Args:
  737. test_state: A state.
  738. router_data: The router data fixture.
  739. """
  740. test_state.router = RouterData(router_data)
  741. assert test_state.router.session.client_ip == "127.0.0.1"
  742. def test_get_current_page(test_state):
  743. assert test_state.router.page.path == ""
  744. route = "mypage/subpage"
  745. test_state.router = RouterData({RouteVar.PATH: route})
  746. assert test_state.router.page.path == route
  747. def test_get_query_params(test_state):
  748. assert test_state.router.page.params == {}
  749. params = {"p1": "a", "p2": "b"}
  750. test_state.router = RouterData({RouteVar.QUERY: params})
  751. assert dict(test_state.router.page.params) == params
  752. def test_add_var():
  753. class DynamicState(BaseState):
  754. pass
  755. ds1 = DynamicState()
  756. assert "dynamic_int" not in ds1.__dict__
  757. assert not hasattr(ds1, "dynamic_int")
  758. ds1.add_var("dynamic_int", int, 42)
  759. # Existing instances get the BaseVar
  760. assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # type: ignore
  761. # New instances get an actual value with the default
  762. assert DynamicState().dynamic_int == 42
  763. ds1.add_var("dynamic_list", List[int], [5, 10])
  764. assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # type: ignore
  765. ds2 = DynamicState()
  766. assert ds2.dynamic_list == [5, 10]
  767. ds2.dynamic_list.append(15)
  768. assert ds2.dynamic_list == [5, 10, 15]
  769. assert DynamicState().dynamic_list == [5, 10]
  770. ds1.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  771. assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  772. assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  773. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  774. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  775. def test_add_var_default_handlers(test_state):
  776. test_state.add_var("rand_int", int, 10)
  777. assert "set_rand_int" in test_state.event_handlers
  778. assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
  779. class InterdependentState(BaseState):
  780. """A state with 3 vars and 3 computed vars.
  781. x: a variable that no computed var depends on
  782. v1: a varable that one computed var directly depeneds on
  783. _v2: a backend variable that one computed var directly depends on
  784. v1x2: a computed var that depends on v1
  785. v2x2: a computed var that depends on backend var _v2
  786. v1x2x2: a computed var that depends on computed var v1x2
  787. """
  788. x: int = 0
  789. v1: int = 0
  790. _v2: int = 1
  791. @rx.var(cache=True)
  792. def v1x2(self) -> int:
  793. """Depends on var v1.
  794. Returns:
  795. Var v1 multiplied by 2
  796. """
  797. return self.v1 * 2
  798. @rx.var(cache=True)
  799. def v2x2(self) -> int:
  800. """Depends on backend var _v2.
  801. Returns:
  802. backend var _v2 multiplied by 2
  803. """
  804. return self._v2 * 2
  805. @rx.var(cache=True, backend=True)
  806. def v2x2_backend(self) -> int:
  807. """Depends on backend var _v2.
  808. Returns:
  809. backend var _v2 multiplied by 2
  810. """
  811. return self._v2 * 2
  812. @rx.var(cache=True)
  813. def v1x2x2(self) -> int:
  814. """Depends on ComputedVar v1x2.
  815. Returns:
  816. ComputedVar v1x2 multiplied by 2
  817. """
  818. return self.v1x2 * 2 # type: ignore
  819. @rx.var(cache=True)
  820. def _v3(self) -> int:
  821. """Depends on backend var _v2.
  822. Returns:
  823. The value of the backend variable.
  824. """
  825. return self._v2
  826. @rx.var(cache=True)
  827. def v3x2(self) -> int:
  828. """Depends on ComputedVar _v3.
  829. Returns:
  830. ComputedVar _v3 multiplied by 2
  831. """
  832. return self._v3 * 2
  833. @pytest.fixture
  834. def interdependent_state() -> BaseState:
  835. """A state with varying dependency between vars.
  836. Returns:
  837. instance of InterdependentState
  838. """
  839. s = InterdependentState()
  840. s.dict() # prime initial relationships by accessing all ComputedVars
  841. return s
  842. def test_interdependent_state_initial_dict() -> None:
  843. s = InterdependentState()
  844. state_name = s.get_name()
  845. d = s.dict(initial=True)[state_name]
  846. d.pop("router")
  847. assert d == {
  848. "x": 0,
  849. "v1": 0,
  850. "v1x2": 0,
  851. "v2x2": 2,
  852. "v1x2x2": 0,
  853. "v3x2": 2,
  854. }
  855. def test_not_dirty_computed_var_from_var(
  856. interdependent_state: InterdependentState,
  857. ) -> None:
  858. """Set Var that no ComputedVar depends on, expect no recalculation.
  859. Args:
  860. interdependent_state: A state with varying Var dependencies.
  861. """
  862. interdependent_state.x = 5
  863. assert interdependent_state.get_delta() == {
  864. interdependent_state.get_full_name(): {"x": 5},
  865. }
  866. def test_dirty_computed_var_from_var(interdependent_state: InterdependentState) -> None:
  867. """Set Var that ComputedVar depends on, expect recalculation.
  868. The other ComputedVar depends on the changed ComputedVar and should also be
  869. recalculated. No other ComputedVars should be recalculated.
  870. Args:
  871. interdependent_state: A state with varying Var dependencies.
  872. """
  873. interdependent_state.v1 = 1
  874. assert interdependent_state.get_delta() == {
  875. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  876. }
  877. def test_dirty_computed_var_from_backend_var(
  878. interdependent_state: InterdependentState,
  879. ) -> None:
  880. """Set backend var that ComputedVar depends on, expect recalculation.
  881. Args:
  882. interdependent_state: A state with varying Var dependencies.
  883. """
  884. # Accessing ._v3 returns the immutable var it represents instead of the actual computed var
  885. # assert InterdependentState._v3._backend is True
  886. interdependent_state._v2 = 2
  887. assert interdependent_state.get_delta() == {
  888. interdependent_state.get_full_name(): {"v2x2": 4, "v3x2": 4},
  889. }
  890. def test_per_state_backend_var(interdependent_state: InterdependentState) -> None:
  891. """Set backend var on one instance, expect no affect in other instances.
  892. Args:
  893. interdependent_state: A state with varying Var dependencies.
  894. """
  895. s2 = InterdependentState()
  896. assert s2._v2 == interdependent_state._v2
  897. interdependent_state._v2 = 2
  898. assert s2._v2 != interdependent_state._v2
  899. s3 = InterdependentState()
  900. assert s3._v2 != interdependent_state._v2
  901. # both s2 and s3 should still have the default value
  902. assert s2._v2 == s3._v2
  903. # changing s2._v2 should not affect others
  904. s2._v2 = 4
  905. assert s2._v2 != interdependent_state._v2
  906. assert s2._v2 != s3._v2
  907. def test_child_state():
  908. """Test that the child state computed vars can reference parent state vars."""
  909. class MainState(BaseState):
  910. v: int = 2
  911. class ChildState(MainState):
  912. @computed_var
  913. def rendered_var(self):
  914. return self.v
  915. ms = MainState()
  916. cs = ms.substates[ChildState.get_name()]
  917. assert ms.v == 2
  918. assert cs.v == 2
  919. assert cs.rendered_var == 2
  920. def test_conditional_computed_vars():
  921. """Test that computed vars can have conditionals."""
  922. class MainState(BaseState):
  923. flag: bool = False
  924. t1: str = "a"
  925. t2: str = "b"
  926. @computed_var
  927. def rendered_var(self) -> str:
  928. if self.flag:
  929. return self.t1
  930. return self.t2
  931. ms = MainState()
  932. # Initially there are no dirty computed vars.
  933. assert ms._dirty_computed_vars(from_vars={"flag"}) == {"rendered_var"}
  934. assert ms._dirty_computed_vars(from_vars={"t2"}) == {"rendered_var"}
  935. assert ms._dirty_computed_vars(from_vars={"t1"}) == {"rendered_var"}
  936. assert ms.computed_vars["rendered_var"]._deps(objclass=MainState) == {
  937. "flag",
  938. "t1",
  939. "t2",
  940. }
  941. def test_event_handlers_convert_to_fns(test_state, child_state):
  942. """Test that when the state is initialized, event handlers are converted to fns.
  943. Args:
  944. test_state: A state with event handlers.
  945. child_state: A child state with event handlers.
  946. """
  947. # The class instances should be event handlers.
  948. assert isinstance(TestState.do_something, EventHandler)
  949. assert isinstance(ChildState.change_both, EventHandler)
  950. # The object instances should be fns.
  951. test_state.do_something()
  952. child_state.change_both(value="goose", count=9)
  953. assert child_state.value == "GOOSE"
  954. assert child_state.count == 18
  955. def test_event_handlers_call_other_handlers():
  956. """Test that event handlers can call other event handlers."""
  957. class MainState(BaseState):
  958. v: int = 0
  959. def set_v(self, v: int):
  960. self.v = v
  961. def set_v2(self, v: int):
  962. self.set_v(v)
  963. class SubState(MainState):
  964. def set_v3(self, v: int):
  965. self.set_v2(v)
  966. class SubSubState(SubState):
  967. def set_v4(self, v: int):
  968. self.set_v(v)
  969. ms = MainState()
  970. ms.set_v2(1)
  971. assert ms.v == 1
  972. # ensure handler can be called from substate
  973. ms.substates[SubState.get_name()].set_v3(2)
  974. assert ms.v == 2
  975. # ensure handler can be called from substate (referencing grandparent handler)
  976. ms.get_substate(tuple(SubSubState.get_full_name().split("."))).set_v4(3)
  977. assert ms.v == 3
  978. def test_computed_var_cached():
  979. """Test that a ComputedVar doesn't recalculate when accessed."""
  980. comp_v_calls = 0
  981. class ComputedState(BaseState):
  982. v: int = 0
  983. @rx.var(cache=True)
  984. def comp_v(self) -> int:
  985. nonlocal comp_v_calls
  986. comp_v_calls += 1
  987. return self.v
  988. cs = ComputedState()
  989. assert cs.dict()[cs.get_full_name()]["v"] == 0
  990. assert comp_v_calls == 1
  991. assert cs.dict()[cs.get_full_name()]["comp_v"] == 0
  992. assert comp_v_calls == 1
  993. assert cs.comp_v == 0
  994. assert comp_v_calls == 1
  995. cs.v = 1
  996. assert comp_v_calls == 1
  997. assert cs.comp_v == 1
  998. assert comp_v_calls == 2
  999. def test_computed_var_cached_depends_on_non_cached():
  1000. """Test that a cached var is recalculated if it depends on non-cached ComputedVar."""
  1001. class ComputedState(BaseState):
  1002. v: int = 0
  1003. @rx.var
  1004. def no_cache_v(self) -> int:
  1005. return self.v
  1006. @rx.var(cache=True)
  1007. def dep_v(self) -> int:
  1008. return self.no_cache_v # type: ignore
  1009. @rx.var(cache=True)
  1010. def comp_v(self) -> int:
  1011. return self.v
  1012. cs = ComputedState()
  1013. assert cs.dirty_vars == set()
  1014. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  1015. cs._clean()
  1016. assert cs.dirty_vars == set()
  1017. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  1018. cs._clean()
  1019. assert cs.dirty_vars == set()
  1020. cs.v = 1
  1021. assert cs.dirty_vars == {"v", "comp_v", "dep_v", "no_cache_v"}
  1022. assert cs.get_delta() == {
  1023. cs.get_name(): {"v": 1, "no_cache_v": 1, "dep_v": 1, "comp_v": 1}
  1024. }
  1025. cs._clean()
  1026. assert cs.dirty_vars == set()
  1027. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  1028. cs._clean()
  1029. assert cs.dirty_vars == set()
  1030. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  1031. cs._clean()
  1032. assert cs.dirty_vars == set()
  1033. def test_computed_var_depends_on_parent_non_cached():
  1034. """Child state cached var that depends on parent state un cached var is always recalculated."""
  1035. counter = 0
  1036. class ParentState(BaseState):
  1037. @rx.var
  1038. def no_cache_v(self) -> int:
  1039. nonlocal counter
  1040. counter += 1
  1041. return counter
  1042. class ChildState(ParentState):
  1043. @rx.var(cache=True)
  1044. def dep_v(self) -> int:
  1045. return self.no_cache_v # type: ignore
  1046. ps = ParentState()
  1047. cs = ps.substates[ChildState.get_name()]
  1048. assert ps.dirty_vars == set()
  1049. assert cs.dirty_vars == set()
  1050. dict1 = json.loads(json_dumps(ps.dict()))
  1051. assert dict1[ps.get_full_name()] == {
  1052. "no_cache_v": 1,
  1053. "router": formatted_router,
  1054. }
  1055. assert dict1[cs.get_full_name()] == {"dep_v": 2}
  1056. dict2 = json.loads(json_dumps(ps.dict()))
  1057. assert dict2[ps.get_full_name()] == {
  1058. "no_cache_v": 3,
  1059. "router": formatted_router,
  1060. }
  1061. assert dict2[cs.get_full_name()] == {"dep_v": 4}
  1062. dict3 = json.loads(json_dumps(ps.dict()))
  1063. assert dict3[ps.get_full_name()] == {
  1064. "no_cache_v": 5,
  1065. "router": formatted_router,
  1066. }
  1067. assert dict3[cs.get_full_name()] == {"dep_v": 6}
  1068. assert counter == 6
  1069. @pytest.mark.parametrize("use_partial", [True, False])
  1070. def test_cached_var_depends_on_event_handler(use_partial: bool):
  1071. """A cached var that calls an event handler calculates deps correctly.
  1072. Args:
  1073. use_partial: if true, replace the EventHandler with functools.partial
  1074. """
  1075. counter = 0
  1076. class HandlerState(BaseState):
  1077. x: int = 42
  1078. def handler(self):
  1079. self.x = self.x + 1
  1080. @rx.var(cache=True)
  1081. def cached_x_side_effect(self) -> int:
  1082. self.handler()
  1083. nonlocal counter
  1084. counter += 1
  1085. return counter
  1086. if use_partial:
  1087. HandlerState.handler = functools.partial(HandlerState.handler.fn)
  1088. assert isinstance(HandlerState.handler, functools.partial)
  1089. else:
  1090. assert isinstance(HandlerState.handler, EventHandler)
  1091. s = HandlerState()
  1092. assert "cached_x_side_effect" in s._computed_var_dependencies["x"]
  1093. assert s.cached_x_side_effect == 1
  1094. assert s.x == 43
  1095. s.handler()
  1096. assert s.cached_x_side_effect == 2
  1097. assert s.x == 45
  1098. def test_computed_var_dependencies():
  1099. """Test that a ComputedVar correctly tracks its dependencies."""
  1100. class ComputedState(BaseState):
  1101. v: int = 0
  1102. w: int = 0
  1103. x: int = 0
  1104. y: List[int] = [1, 2, 3]
  1105. _z: List[int] = [1, 2, 3]
  1106. @property
  1107. def testprop(self) -> int:
  1108. return self.v
  1109. @rx.var(cache=True)
  1110. def comp_v(self) -> int:
  1111. """Direct access.
  1112. Returns:
  1113. The value of self.v.
  1114. """
  1115. return self.v
  1116. @rx.var(cache=True, backend=True)
  1117. def comp_v_backend(self) -> int:
  1118. """Direct access backend var.
  1119. Returns:
  1120. The value of self.v.
  1121. """
  1122. return self.v
  1123. @rx.var(cache=True)
  1124. def comp_v_via_property(self) -> int:
  1125. """Access v via property.
  1126. Returns:
  1127. The value of v via property.
  1128. """
  1129. return self.testprop
  1130. @rx.var(cache=True)
  1131. def comp_w(self):
  1132. """Nested lambda.
  1133. Returns:
  1134. A lambda that returns the value of self.w.
  1135. """
  1136. return lambda: self.w
  1137. @rx.var(cache=True)
  1138. def comp_x(self):
  1139. """Nested function.
  1140. Returns:
  1141. A function that returns the value of self.x.
  1142. """
  1143. def _():
  1144. return self.x
  1145. return _
  1146. @rx.var(cache=True)
  1147. def comp_y(self) -> List[int]:
  1148. """Comprehension iterating over attribute.
  1149. Returns:
  1150. A list of the values of self.y.
  1151. """
  1152. return [round(y) for y in self.y]
  1153. @rx.var(cache=True)
  1154. def comp_z(self) -> List[bool]:
  1155. """Comprehension accesses attribute.
  1156. Returns:
  1157. A list of whether the values 0-4 are in self._z.
  1158. """
  1159. return [z in self._z for z in range(5)]
  1160. cs = ComputedState()
  1161. assert cs._computed_var_dependencies["v"] == {
  1162. "comp_v",
  1163. "comp_v_backend",
  1164. "comp_v_via_property",
  1165. }
  1166. assert cs._computed_var_dependencies["w"] == {"comp_w"}
  1167. assert cs._computed_var_dependencies["x"] == {"comp_x"}
  1168. assert cs._computed_var_dependencies["y"] == {"comp_y"}
  1169. assert cs._computed_var_dependencies["_z"] == {"comp_z"}
  1170. def test_backend_method():
  1171. """A method with leading underscore should be callable from event handler."""
  1172. class BackendMethodState(BaseState):
  1173. def _be_method(self):
  1174. return True
  1175. def handler(self):
  1176. assert self._be_method()
  1177. bms = BackendMethodState()
  1178. bms.handler()
  1179. assert bms._be_method()
  1180. def test_setattr_of_mutable_types(mutable_state: MutableTestState):
  1181. """Test that mutable types are converted to corresponding Reflex wrappers.
  1182. Args:
  1183. mutable_state: A test state.
  1184. """
  1185. array = mutable_state.array
  1186. hashmap = mutable_state.hashmap
  1187. test_set = mutable_state.test_set
  1188. sqla_model = mutable_state.sqla_model
  1189. assert isinstance(array, MutableProxy)
  1190. assert isinstance(array, list)
  1191. assert isinstance(array[1], MutableProxy)
  1192. assert isinstance(array[1], list)
  1193. assert isinstance(array[2], MutableProxy)
  1194. assert isinstance(array[2], dict)
  1195. assert isinstance(hashmap, MutableProxy)
  1196. assert isinstance(hashmap, dict)
  1197. assert isinstance(hashmap["key"], MutableProxy)
  1198. assert isinstance(hashmap["key"], list)
  1199. assert isinstance(hashmap["third_key"], MutableProxy)
  1200. assert isinstance(hashmap["third_key"], dict)
  1201. assert isinstance(test_set, MutableProxy)
  1202. assert isinstance(test_set, set)
  1203. assert isinstance(mutable_state.custom, MutableProxy)
  1204. assert isinstance(mutable_state.custom.array, MutableProxy)
  1205. assert isinstance(mutable_state.custom.array, list)
  1206. assert isinstance(mutable_state.custom.hashmap, MutableProxy)
  1207. assert isinstance(mutable_state.custom.hashmap, dict)
  1208. assert isinstance(mutable_state.custom.test_set, MutableProxy)
  1209. assert isinstance(mutable_state.custom.test_set, set)
  1210. assert isinstance(mutable_state.custom.custom, MutableProxy)
  1211. assert isinstance(sqla_model, MutableProxy)
  1212. assert isinstance(sqla_model, MutableSQLAModel)
  1213. assert isinstance(sqla_model.strlist, MutableProxy)
  1214. assert isinstance(sqla_model.strlist, list)
  1215. assert isinstance(sqla_model.hashmap, MutableProxy)
  1216. assert isinstance(sqla_model.hashmap, dict)
  1217. assert isinstance(sqla_model.test_set, MutableProxy)
  1218. assert isinstance(sqla_model.test_set, set)
  1219. mutable_state.reassign_mutables()
  1220. array = mutable_state.array
  1221. hashmap = mutable_state.hashmap
  1222. test_set = mutable_state.test_set
  1223. sqla_model = mutable_state.sqla_model
  1224. assert isinstance(array, MutableProxy)
  1225. assert isinstance(array, list)
  1226. assert isinstance(array[1], MutableProxy)
  1227. assert isinstance(array[1], list)
  1228. assert isinstance(array[2], MutableProxy)
  1229. assert isinstance(array[2], dict)
  1230. assert isinstance(hashmap, MutableProxy)
  1231. assert isinstance(hashmap, dict)
  1232. assert isinstance(hashmap["mod_key"], MutableProxy)
  1233. assert isinstance(hashmap["mod_key"], list)
  1234. assert isinstance(hashmap["mod_third_key"], MutableProxy)
  1235. assert isinstance(hashmap["mod_third_key"], dict)
  1236. assert isinstance(test_set, MutableProxy)
  1237. assert isinstance(test_set, set)
  1238. assert isinstance(sqla_model, MutableProxy)
  1239. assert isinstance(sqla_model, MutableSQLAModel)
  1240. assert isinstance(sqla_model.strlist, MutableProxy)
  1241. assert isinstance(sqla_model.strlist, list)
  1242. assert isinstance(sqla_model.hashmap, MutableProxy)
  1243. assert isinstance(sqla_model.hashmap, dict)
  1244. assert isinstance(sqla_model.test_set, MutableProxy)
  1245. assert isinstance(sqla_model.test_set, set)
  1246. def test_error_on_state_method_shadow():
  1247. """Test that an error is thrown when an event handler shadows a state method."""
  1248. with pytest.raises(NameError) as err:
  1249. class InvalidTest(BaseState):
  1250. def reset(self):
  1251. pass
  1252. assert (
  1253. err.value.args[0]
  1254. == "The event handler name `reset` shadows a builtin State method; use a different name instead"
  1255. )
  1256. @pytest.mark.asyncio
  1257. async def test_state_with_invalid_yield(capsys, mock_app):
  1258. """Test that an error is thrown when a state yields an invalid value.
  1259. Args:
  1260. capsys: Pytest fixture for capture standard streams.
  1261. mock_app: Mock app fixture.
  1262. """
  1263. class StateWithInvalidYield(BaseState):
  1264. """A state that yields an invalid value."""
  1265. def invalid_handler(self):
  1266. """Invalid handler.
  1267. Yields:
  1268. an invalid value.
  1269. """
  1270. yield 1
  1271. invalid_state = StateWithInvalidYield()
  1272. async for update in invalid_state._process(
  1273. rx.event.Event(token="fake_token", name="invalid_handler")
  1274. ):
  1275. assert not update.delta
  1276. if Toaster.is_used:
  1277. assert update.events == rx.event.fix_events(
  1278. [
  1279. rx.toast(
  1280. "An error occurred.",
  1281. description="TypeError: Your handler test_state_with_invalid_yield.<locals>.StateWithInvalidYield.invalid_handler must only return/yield: None, Events or other EventHandlers referenced by their class (not using `self`).<br/>See logs for details.",
  1282. level="error",
  1283. id="backend_error",
  1284. position="top-center",
  1285. style={"width": "500px"},
  1286. ) # type: ignore
  1287. ],
  1288. token="",
  1289. )
  1290. else:
  1291. assert update.events == rx.event.fix_events(
  1292. [
  1293. rx.window_alert(
  1294. "An error occurred.\nContact the website administrator."
  1295. )
  1296. ],
  1297. token="",
  1298. )
  1299. captured = capsys.readouterr()
  1300. assert "must only return/yield: None, Events or other EventHandlers" in captured.out
  1301. @pytest_asyncio.fixture(
  1302. loop_scope="function", scope="function", params=["in_process", "disk", "redis"]
  1303. )
  1304. async def state_manager(request) -> AsyncGenerator[StateManager, None]:
  1305. """Instance of state manager parametrized for redis and in-process.
  1306. Args:
  1307. request: pytest request object.
  1308. Yields:
  1309. A state manager instance
  1310. """
  1311. state_manager = StateManager.create(state=TestState)
  1312. if request.param == "redis":
  1313. if not isinstance(state_manager, StateManagerRedis):
  1314. pytest.skip("Test requires redis")
  1315. elif request.param == "disk":
  1316. # explicitly NOT using redis
  1317. state_manager = StateManagerDisk(state=TestState)
  1318. assert not state_manager._states_locks
  1319. else:
  1320. state_manager = StateManagerMemory(state=TestState)
  1321. assert not state_manager._states_locks
  1322. yield state_manager
  1323. if isinstance(state_manager, StateManagerRedis):
  1324. await state_manager.close()
  1325. @pytest.fixture()
  1326. def substate_token(state_manager, token):
  1327. """A token + substate name for looking up in state manager.
  1328. Args:
  1329. state_manager: A state manager instance.
  1330. token: A token.
  1331. Returns:
  1332. Token concatenated with the state_manager's state full_name.
  1333. """
  1334. return _substate_key(token, state_manager.state)
  1335. @pytest.mark.asyncio
  1336. async def test_state_manager_modify_state(
  1337. state_manager: StateManager, token: str, substate_token: str
  1338. ):
  1339. """Test that the state manager can modify a state exclusively.
  1340. Args:
  1341. state_manager: A state manager instance.
  1342. token: A token.
  1343. substate_token: A token + substate name for looking up in state manager.
  1344. """
  1345. async with state_manager.modify_state(substate_token) as state:
  1346. if isinstance(state_manager, StateManagerRedis):
  1347. assert await state_manager.redis.get(f"{token}_lock")
  1348. elif isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  1349. assert token in state_manager._states_locks
  1350. assert state_manager._states_locks[token].locked()
  1351. # Should be able to write proxy objects inside mutables
  1352. complex_1 = state.complex[1]
  1353. assert isinstance(complex_1, MutableProxy)
  1354. state.complex[3] = complex_1
  1355. # lock should be dropped after exiting the context
  1356. if isinstance(state_manager, StateManagerRedis):
  1357. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1358. elif isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  1359. assert not state_manager._states_locks[token].locked()
  1360. # separate instances should NOT share locks
  1361. sm2 = state_manager.__class__(state=TestState)
  1362. assert sm2._state_manager_lock is state_manager._state_manager_lock
  1363. assert not sm2._states_locks
  1364. if state_manager._states_locks:
  1365. assert sm2._states_locks != state_manager._states_locks
  1366. @pytest.mark.asyncio
  1367. async def test_state_manager_contend(
  1368. state_manager: StateManager, token: str, substate_token: str
  1369. ):
  1370. """Multiple coroutines attempting to access the same state.
  1371. Args:
  1372. state_manager: A state manager instance.
  1373. token: A token.
  1374. substate_token: A token + substate name for looking up in state manager.
  1375. """
  1376. n_coroutines = 10
  1377. exp_num1 = 10
  1378. async with state_manager.modify_state(substate_token) as state:
  1379. state.num1 = 0
  1380. async def _coro():
  1381. async with state_manager.modify_state(substate_token) as state:
  1382. await asyncio.sleep(0.01)
  1383. state.num1 += 1
  1384. tasks = [asyncio.create_task(_coro()) for _ in range(n_coroutines)]
  1385. for f in asyncio.as_completed(tasks):
  1386. await f
  1387. assert (await state_manager.get_state(substate_token)).num1 == exp_num1
  1388. if isinstance(state_manager, StateManagerRedis):
  1389. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1390. elif isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  1391. assert token in state_manager._states_locks
  1392. assert not state_manager._states_locks[token].locked()
  1393. @pytest_asyncio.fixture(loop_scope="function", scope="function")
  1394. async def state_manager_redis() -> AsyncGenerator[StateManager, None]:
  1395. """Instance of state manager for redis only.
  1396. Yields:
  1397. A state manager instance
  1398. """
  1399. state_manager = StateManager.create(TestState)
  1400. if not isinstance(state_manager, StateManagerRedis):
  1401. pytest.skip("Test requires redis")
  1402. yield state_manager
  1403. await state_manager.close()
  1404. @pytest.fixture()
  1405. def substate_token_redis(state_manager_redis, token):
  1406. """A token + substate name for looking up in state manager.
  1407. Args:
  1408. state_manager_redis: A state manager instance.
  1409. token: A token.
  1410. Returns:
  1411. Token concatenated with the state_manager's state full_name.
  1412. """
  1413. return _substate_key(token, state_manager_redis.state)
  1414. @pytest.mark.asyncio
  1415. async def test_state_manager_lock_expire(
  1416. state_manager_redis: StateManager, token: str, substate_token_redis: str
  1417. ):
  1418. """Test that the state manager lock expires and raises exception exiting context.
  1419. Args:
  1420. state_manager_redis: A state manager instance.
  1421. token: A token.
  1422. substate_token_redis: A token + substate name for looking up in state manager.
  1423. """
  1424. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1425. async with state_manager_redis.modify_state(substate_token_redis):
  1426. await asyncio.sleep(0.01)
  1427. with pytest.raises(LockExpiredError):
  1428. async with state_manager_redis.modify_state(substate_token_redis):
  1429. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1430. @pytest.mark.asyncio
  1431. async def test_state_manager_lock_expire_contend(
  1432. state_manager_redis: StateManager, token: str, substate_token_redis: str
  1433. ):
  1434. """Test that the state manager lock expires and queued waiters proceed.
  1435. Args:
  1436. state_manager_redis: A state manager instance.
  1437. token: A token.
  1438. substate_token_redis: A token + substate name for looking up in state manager.
  1439. """
  1440. exp_num1 = 4252
  1441. unexp_num1 = 666
  1442. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1443. order = []
  1444. async def _coro_blocker():
  1445. async with state_manager_redis.modify_state(substate_token_redis) as state:
  1446. order.append("blocker")
  1447. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1448. state.num1 = unexp_num1
  1449. async def _coro_waiter():
  1450. while "blocker" not in order:
  1451. await asyncio.sleep(0.005)
  1452. async with state_manager_redis.modify_state(substate_token_redis) as state:
  1453. order.append("waiter")
  1454. assert state.num1 != unexp_num1
  1455. state.num1 = exp_num1
  1456. tasks = [
  1457. asyncio.create_task(_coro_blocker()),
  1458. asyncio.create_task(_coro_waiter()),
  1459. ]
  1460. with pytest.raises(LockExpiredError):
  1461. await tasks[0]
  1462. await tasks[1]
  1463. assert order == ["blocker", "waiter"]
  1464. assert (await state_manager_redis.get_state(substate_token_redis)).num1 == exp_num1
  1465. @pytest.fixture(scope="function")
  1466. def mock_app_simple(monkeypatch) -> rx.App:
  1467. """Simple Mock app fixture.
  1468. Args:
  1469. monkeypatch: Pytest monkeypatch object.
  1470. Returns:
  1471. The app, after mocking out prerequisites.get_app()
  1472. """
  1473. app = App(state=TestState)
  1474. app_module = Mock()
  1475. setattr(app_module, CompileVars.APP, app)
  1476. app.state = TestState
  1477. app.event_namespace.emit = AsyncMock() # type: ignore
  1478. def _mock_get_app(*args, **kwargs):
  1479. return app_module
  1480. monkeypatch.setattr(prerequisites, "get_app", _mock_get_app)
  1481. return app
  1482. @pytest.fixture(scope="function")
  1483. def mock_app(mock_app_simple: rx.App, state_manager: StateManager) -> rx.App:
  1484. """Mock app fixture.
  1485. Args:
  1486. mock_app_simple: A simple mock app.
  1487. state_manager: A state manager.
  1488. Returns:
  1489. The app, after mocking out prerequisites.get_app()
  1490. """
  1491. mock_app_simple._state_manager = state_manager
  1492. return mock_app_simple
  1493. @pytest.mark.asyncio
  1494. async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
  1495. """Test that the state proxy works.
  1496. Args:
  1497. grandchild_state: A grandchild state.
  1498. mock_app: An app that will be returned by `get_app()`
  1499. """
  1500. child_state = grandchild_state.parent_state
  1501. assert child_state is not None
  1502. parent_state = child_state.parent_state
  1503. assert parent_state is not None
  1504. if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
  1505. mock_app.state_manager.states[parent_state.router.session.client_token] = (
  1506. parent_state
  1507. )
  1508. sp = StateProxy(grandchild_state)
  1509. assert sp.__wrapped__ == grandchild_state
  1510. assert sp._self_substate_path == tuple(grandchild_state.get_full_name().split("."))
  1511. assert sp._self_app is mock_app
  1512. assert not sp._self_mutable
  1513. assert sp._self_actx is None
  1514. # cannot use normal contextmanager protocol
  1515. with pytest.raises(TypeError), sp:
  1516. pass
  1517. with pytest.raises(ImmutableStateError):
  1518. # cannot directly modify state proxy outside of async context
  1519. sp.value2 = "16"
  1520. with pytest.raises(ImmutableStateError):
  1521. # Cannot get_state
  1522. await sp.get_state(ChildState)
  1523. with pytest.raises(ImmutableStateError):
  1524. # Cannot access get_substate
  1525. sp.get_substate([])
  1526. with pytest.raises(ImmutableStateError):
  1527. # Cannot access parent state
  1528. sp.parent_state.get_name()
  1529. with pytest.raises(ImmutableStateError):
  1530. # Cannot access substates
  1531. sp.substates[""]
  1532. async with sp:
  1533. assert sp._self_actx is not None
  1534. assert sp._self_mutable # proxy is mutable inside context
  1535. if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
  1536. # For in-process store, only one instance of the state exists
  1537. assert sp.__wrapped__ is grandchild_state
  1538. else:
  1539. # When redis is used, a new+updated instance is assigned to the proxy
  1540. assert sp.__wrapped__ is not grandchild_state
  1541. sp.value2 = "42"
  1542. assert not sp._self_mutable # proxy is not mutable after exiting context
  1543. assert sp._self_actx is None
  1544. assert sp.value2 == "42"
  1545. # Get the state from the state manager directly and check that the value is updated
  1546. gotten_state = await mock_app.state_manager.get_state(
  1547. _substate_key(grandchild_state.router.session.client_token, grandchild_state)
  1548. )
  1549. if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
  1550. # For in-process store, only one instance of the state exists
  1551. assert gotten_state is parent_state
  1552. else:
  1553. assert gotten_state is not parent_state
  1554. gotten_grandchild_state = gotten_state.get_substate(sp._self_substate_path)
  1555. assert gotten_grandchild_state is not None
  1556. assert gotten_grandchild_state.value2 == "42"
  1557. # ensure state update was emitted
  1558. assert mock_app.event_namespace is not None
  1559. mock_app.event_namespace.emit.assert_called_once()
  1560. mcall = mock_app.event_namespace.emit.mock_calls[0]
  1561. assert mcall.args[0] == str(SocketEvent.EVENT)
  1562. assert json.loads(mcall.args[1]) == dataclasses.asdict(
  1563. StateUpdate(
  1564. delta={
  1565. parent_state.get_full_name(): {
  1566. "upper": "",
  1567. "sum": 3.14,
  1568. },
  1569. grandchild_state.get_full_name(): {
  1570. "value2": "42",
  1571. },
  1572. GrandchildState3.get_full_name(): {
  1573. "computed": "",
  1574. },
  1575. }
  1576. )
  1577. )
  1578. assert mcall.kwargs["to"] == grandchild_state.router.session.session_id
  1579. class BackgroundTaskState(BaseState):
  1580. """A state with a background task."""
  1581. order: List[str] = []
  1582. dict_list: Dict[str, List[int]] = {"foo": [1, 2, 3]}
  1583. @rx.var
  1584. def computed_order(self) -> List[str]:
  1585. """Get the order as a computed var.
  1586. Returns:
  1587. The value of 'order' var.
  1588. """
  1589. return self.order
  1590. @rx.event(background=True)
  1591. async def background_task(self):
  1592. """A background task that updates the state."""
  1593. async with self:
  1594. assert not self.order
  1595. self.order.append("background_task:start")
  1596. assert isinstance(self, StateProxy)
  1597. with pytest.raises(ImmutableStateError):
  1598. self.order.append("bad idea")
  1599. with pytest.raises(ImmutableStateError):
  1600. # Even nested access to mutables raises an exception.
  1601. self.dict_list["foo"].append(42)
  1602. with pytest.raises(ImmutableStateError):
  1603. # Direct calling another handler that modifies state raises an exception.
  1604. self.other()
  1605. with pytest.raises(ImmutableStateError):
  1606. # Calling other methods that modify state raises an exception.
  1607. self._private_method()
  1608. # wait for some other event to happen
  1609. while len(self.order) == 1:
  1610. await asyncio.sleep(0.01)
  1611. async with self:
  1612. pass # update proxy instance
  1613. async with self:
  1614. # Methods on ImmutableMutableProxy should return their wrapped return value.
  1615. assert self.dict_list.pop("foo") == [1, 2, 3]
  1616. self.order.append("background_task:stop")
  1617. self.other() # direct calling event handlers works in context
  1618. self._private_method()
  1619. @rx.event(background=True)
  1620. async def background_task_reset(self):
  1621. """A background task that resets the state."""
  1622. with pytest.raises(ImmutableStateError):
  1623. # Resetting the state should be explicitly blocked.
  1624. self.reset()
  1625. async with self:
  1626. self.order.append("foo")
  1627. self.reset()
  1628. assert not self.order
  1629. async with self:
  1630. self.order.append("reset")
  1631. @rx.event(background=True)
  1632. async def background_task_generator(self):
  1633. """A background task generator that does nothing.
  1634. Yields:
  1635. None
  1636. """
  1637. yield
  1638. def other(self):
  1639. """Some other event that updates the state."""
  1640. self.order.append("other")
  1641. def _private_method(self):
  1642. """Some private method that updates the state."""
  1643. self.order.append("private")
  1644. async def bad_chain1(self):
  1645. """Test that a background task cannot be chained."""
  1646. await self.background_task()
  1647. async def bad_chain2(self):
  1648. """Test that a background task generator cannot be chained."""
  1649. async for _foo in self.background_task_generator():
  1650. pass
  1651. @pytest.mark.asyncio
  1652. async def test_background_task_no_block(mock_app: rx.App, token: str):
  1653. """Test that a background task does not block other events.
  1654. Args:
  1655. mock_app: An app that will be returned by `get_app()`
  1656. token: A token.
  1657. """
  1658. router_data = {"query": {}}
  1659. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1660. async for update in rx.app.process( # type: ignore
  1661. mock_app,
  1662. Event(
  1663. token=token,
  1664. name=f"{BackgroundTaskState.get_full_name()}.background_task",
  1665. router_data=router_data,
  1666. payload={},
  1667. ),
  1668. sid="",
  1669. headers={},
  1670. client_ip="",
  1671. ):
  1672. # background task returns empty update immediately
  1673. assert update == StateUpdate()
  1674. # wait for the coroutine to start
  1675. await asyncio.sleep(0.5 if CI else 0.1)
  1676. assert len(mock_app.background_tasks) == 1
  1677. # Process another normal event
  1678. async for update in rx.app.process( # type: ignore
  1679. mock_app,
  1680. Event(
  1681. token=token,
  1682. name=f"{BackgroundTaskState.get_full_name()}.other",
  1683. router_data=router_data,
  1684. payload={},
  1685. ),
  1686. sid="",
  1687. headers={},
  1688. client_ip="",
  1689. ):
  1690. # other task returns delta
  1691. assert update == StateUpdate(
  1692. delta={
  1693. BackgroundTaskState.get_full_name(): {
  1694. "order": [
  1695. "background_task:start",
  1696. "other",
  1697. ],
  1698. "computed_order": [
  1699. "background_task:start",
  1700. "other",
  1701. ],
  1702. }
  1703. }
  1704. )
  1705. # Explicit wait for background tasks
  1706. for task in tuple(mock_app.background_tasks):
  1707. await task
  1708. assert not mock_app.background_tasks
  1709. exp_order = [
  1710. "background_task:start",
  1711. "other",
  1712. "background_task:stop",
  1713. "other",
  1714. "private",
  1715. ]
  1716. assert (
  1717. await mock_app.state_manager.get_state(
  1718. _substate_key(token, BackgroundTaskState)
  1719. )
  1720. ).order == exp_order
  1721. assert mock_app.event_namespace is not None
  1722. emit_mock = mock_app.event_namespace.emit
  1723. first_ws_message = json.loads(emit_mock.mock_calls[0].args[1])
  1724. assert (
  1725. first_ws_message["delta"][BackgroundTaskState.get_full_name()].pop("router")
  1726. is not None
  1727. )
  1728. assert first_ws_message == {
  1729. "delta": {
  1730. BackgroundTaskState.get_full_name(): {
  1731. "order": ["background_task:start"],
  1732. "computed_order": ["background_task:start"],
  1733. }
  1734. },
  1735. "events": [],
  1736. "final": True,
  1737. }
  1738. for call in emit_mock.mock_calls[1:5]:
  1739. assert json.loads(call.args[1]) == {
  1740. "delta": {
  1741. BackgroundTaskState.get_full_name(): {
  1742. "computed_order": ["background_task:start"],
  1743. }
  1744. },
  1745. "events": [],
  1746. "final": True,
  1747. }
  1748. assert json.loads(emit_mock.mock_calls[-2].args[1]) == {
  1749. "delta": {
  1750. BackgroundTaskState.get_full_name(): {
  1751. "order": exp_order,
  1752. "computed_order": exp_order,
  1753. "dict_list": {},
  1754. }
  1755. },
  1756. "events": [],
  1757. "final": True,
  1758. }
  1759. assert json.loads(emit_mock.mock_calls[-1].args[1]) == {
  1760. "delta": {
  1761. BackgroundTaskState.get_full_name(): {
  1762. "computed_order": exp_order,
  1763. },
  1764. },
  1765. "events": [],
  1766. "final": True,
  1767. }
  1768. @pytest.mark.asyncio
  1769. async def test_background_task_reset(mock_app: rx.App, token: str):
  1770. """Test that a background task calling reset is protected by the state proxy.
  1771. Args:
  1772. mock_app: An app that will be returned by `get_app()`
  1773. token: A token.
  1774. """
  1775. router_data = {"query": {}}
  1776. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1777. async for update in rx.app.process( # type: ignore
  1778. mock_app,
  1779. Event(
  1780. token=token,
  1781. name=f"{BackgroundTaskState.get_name()}.background_task_reset",
  1782. router_data=router_data,
  1783. payload={},
  1784. ),
  1785. sid="",
  1786. headers={},
  1787. client_ip="",
  1788. ):
  1789. # background task returns empty update immediately
  1790. assert update == StateUpdate()
  1791. # Explicit wait for background tasks
  1792. for task in tuple(mock_app.background_tasks):
  1793. await task
  1794. assert not mock_app.background_tasks
  1795. assert (
  1796. await mock_app.state_manager.get_state(
  1797. _substate_key(token, BackgroundTaskState)
  1798. )
  1799. ).order == [
  1800. "reset",
  1801. ]
  1802. @pytest.mark.asyncio
  1803. async def test_background_task_no_chain():
  1804. """Test that a background task cannot be chained."""
  1805. bts = BackgroundTaskState()
  1806. with pytest.raises(RuntimeError):
  1807. await bts.bad_chain1()
  1808. with pytest.raises(RuntimeError):
  1809. await bts.bad_chain2()
  1810. def test_mutable_list(mutable_state: MutableTestState):
  1811. """Test that mutable lists are tracked correctly.
  1812. Args:
  1813. mutable_state: A test state.
  1814. """
  1815. assert not mutable_state.dirty_vars
  1816. def assert_array_dirty():
  1817. assert mutable_state.dirty_vars == {"array"}
  1818. mutable_state._clean()
  1819. assert not mutable_state.dirty_vars
  1820. # Test all list operations
  1821. mutable_state.array.append(42)
  1822. assert_array_dirty()
  1823. mutable_state.array.extend([1, 2, 3])
  1824. assert_array_dirty()
  1825. mutable_state.array.insert(0, 0)
  1826. assert_array_dirty()
  1827. mutable_state.array.pop()
  1828. assert_array_dirty()
  1829. mutable_state.array.remove(42)
  1830. assert_array_dirty()
  1831. mutable_state.array.clear()
  1832. assert_array_dirty()
  1833. mutable_state.array += [1, 2, 3]
  1834. assert_array_dirty()
  1835. mutable_state.array.reverse()
  1836. assert_array_dirty()
  1837. mutable_state.array.sort() # type: ignore[reportCallIssue,reportUnknownMemberType]
  1838. assert_array_dirty()
  1839. mutable_state.array[0] = 666
  1840. assert_array_dirty()
  1841. del mutable_state.array[0]
  1842. assert_array_dirty()
  1843. # Test nested list operations
  1844. mutable_state.array[0] = [1, 2, 3]
  1845. assert_array_dirty()
  1846. mutable_state.array[0].append(4)
  1847. assert_array_dirty()
  1848. assert isinstance(mutable_state.array[0], MutableProxy)
  1849. # Test proxy returned from __iter__
  1850. mutable_state.array = [{}]
  1851. assert_array_dirty()
  1852. assert isinstance(mutable_state.array[0], MutableProxy)
  1853. for item in mutable_state.array:
  1854. assert isinstance(item, MutableProxy)
  1855. item["foo"] = "bar"
  1856. assert_array_dirty()
  1857. def test_mutable_dict(mutable_state: MutableTestState):
  1858. """Test that mutable dicts are tracked correctly.
  1859. Args:
  1860. mutable_state: A test state.
  1861. """
  1862. assert not mutable_state.dirty_vars
  1863. def assert_hashmap_dirty():
  1864. assert mutable_state.dirty_vars == {"hashmap"}
  1865. mutable_state._clean()
  1866. assert not mutable_state.dirty_vars
  1867. # Test all dict operations
  1868. mutable_state.hashmap.update({"new_key": "43"})
  1869. assert_hashmap_dirty()
  1870. assert mutable_state.hashmap.setdefault("another_key", "66") == "another_value"
  1871. assert_hashmap_dirty()
  1872. assert mutable_state.hashmap.setdefault("setdefault_key", "67") == "67"
  1873. assert_hashmap_dirty()
  1874. assert mutable_state.hashmap.setdefault("setdefault_key", "68") == "67"
  1875. assert_hashmap_dirty()
  1876. assert mutable_state.hashmap.pop("new_key") == "43"
  1877. assert_hashmap_dirty()
  1878. mutable_state.hashmap.popitem()
  1879. assert_hashmap_dirty()
  1880. mutable_state.hashmap.clear()
  1881. assert_hashmap_dirty()
  1882. mutable_state.hashmap["new_key"] = "42"
  1883. assert_hashmap_dirty()
  1884. del mutable_state.hashmap["new_key"]
  1885. assert_hashmap_dirty()
  1886. if sys.version_info >= (3, 9):
  1887. mutable_state.hashmap |= {"new_key": "44"}
  1888. assert_hashmap_dirty()
  1889. # Test nested dict operations
  1890. mutable_state.hashmap["array"] = []
  1891. assert_hashmap_dirty()
  1892. mutable_state.hashmap["array"].append("1")
  1893. assert_hashmap_dirty()
  1894. mutable_state.hashmap["dict"] = {}
  1895. assert_hashmap_dirty()
  1896. mutable_state.hashmap["dict"]["key"] = "42"
  1897. assert_hashmap_dirty()
  1898. mutable_state.hashmap["dict"]["dict"] = {}
  1899. assert_hashmap_dirty()
  1900. mutable_state.hashmap["dict"]["dict"]["key"] = "43"
  1901. assert_hashmap_dirty()
  1902. # Test proxy returned from `setdefault` and `get`
  1903. mutable_value = mutable_state.hashmap.setdefault("setdefault_mutable_key", [])
  1904. assert_hashmap_dirty()
  1905. assert mutable_value == []
  1906. assert isinstance(mutable_value, MutableProxy)
  1907. mutable_value.append("foo")
  1908. assert_hashmap_dirty()
  1909. mutable_value_other_ref = mutable_state.hashmap.get("setdefault_mutable_key")
  1910. assert isinstance(mutable_value_other_ref, MutableProxy)
  1911. assert mutable_value is not mutable_value_other_ref
  1912. assert mutable_value == mutable_value_other_ref
  1913. assert not mutable_state.dirty_vars
  1914. mutable_value_other_ref.append("bar")
  1915. assert_hashmap_dirty()
  1916. # `pop` should NOT return a proxy, because the returned value is no longer in the dict
  1917. mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key")
  1918. assert not isinstance(mutable_value_third_ref, MutableProxy)
  1919. assert_hashmap_dirty()
  1920. mutable_value_third_ref.append("baz") # type: ignore[reportUnknownMemberType,reportAttributeAccessIssue,reportUnusedCallResult]
  1921. assert not mutable_state.dirty_vars
  1922. # Unfortunately previous refs still will mark the state dirty... nothing doing about that
  1923. assert mutable_value.pop()
  1924. assert_hashmap_dirty()
  1925. def test_mutable_set(mutable_state: MutableTestState):
  1926. """Test that mutable sets are tracked correctly.
  1927. Args:
  1928. mutable_state: A test state.
  1929. """
  1930. assert not mutable_state.dirty_vars
  1931. def assert_set_dirty():
  1932. assert mutable_state.dirty_vars == {"test_set"}
  1933. mutable_state._clean()
  1934. assert not mutable_state.dirty_vars
  1935. # Test all set operations
  1936. mutable_state.test_set.add(42)
  1937. assert_set_dirty()
  1938. mutable_state.test_set.update([1, 2, 3])
  1939. assert_set_dirty()
  1940. mutable_state.test_set.remove(42)
  1941. assert_set_dirty()
  1942. mutable_state.test_set.discard(3)
  1943. assert_set_dirty()
  1944. mutable_state.test_set.pop()
  1945. assert_set_dirty()
  1946. mutable_state.test_set.intersection_update([1, 2, 3])
  1947. assert_set_dirty()
  1948. mutable_state.test_set.difference_update([99])
  1949. assert_set_dirty()
  1950. mutable_state.test_set.symmetric_difference_update([102, 99])
  1951. assert_set_dirty()
  1952. mutable_state.test_set |= {1, 2, 3}
  1953. assert_set_dirty()
  1954. mutable_state.test_set &= {2, 3, 4}
  1955. assert_set_dirty()
  1956. mutable_state.test_set -= {2}
  1957. assert_set_dirty()
  1958. mutable_state.test_set ^= {42}
  1959. assert_set_dirty()
  1960. mutable_state.test_set.clear()
  1961. assert_set_dirty()
  1962. def test_mutable_custom(mutable_state: MutableTestState):
  1963. """Test that mutable custom types derived from Base are tracked correctly.
  1964. Args:
  1965. mutable_state: A test state.
  1966. """
  1967. assert not mutable_state.dirty_vars
  1968. def assert_custom_dirty():
  1969. assert mutable_state.dirty_vars == {"custom"}
  1970. mutable_state._clean()
  1971. assert not mutable_state.dirty_vars
  1972. mutable_state.custom.foo = "bar"
  1973. assert_custom_dirty()
  1974. mutable_state.custom.array.append("42")
  1975. assert_custom_dirty()
  1976. mutable_state.custom.hashmap["key"] = "value"
  1977. assert_custom_dirty()
  1978. mutable_state.custom.test_set.add("foo")
  1979. assert_custom_dirty()
  1980. mutable_state.custom.custom.bar = "baz"
  1981. assert_custom_dirty()
  1982. def test_mutable_sqla_model(mutable_state: MutableTestState):
  1983. """Test that mutable SQLA models are tracked correctly.
  1984. Args:
  1985. mutable_state: A test state.
  1986. """
  1987. assert not mutable_state.dirty_vars
  1988. def assert_sqla_model_dirty():
  1989. assert mutable_state.dirty_vars == {"sqla_model"}
  1990. mutable_state._clean()
  1991. assert not mutable_state.dirty_vars
  1992. mutable_state.sqla_model.strlist.append("foo")
  1993. assert_sqla_model_dirty()
  1994. mutable_state.sqla_model.hashmap["key"] = "value"
  1995. assert_sqla_model_dirty()
  1996. mutable_state.sqla_model.test_set.add("bar")
  1997. assert_sqla_model_dirty()
  1998. def test_mutable_backend(mutable_state: MutableTestState):
  1999. """Test that mutable backend vars are tracked correctly.
  2000. Args:
  2001. mutable_state: A test state.
  2002. """
  2003. assert not mutable_state.dirty_vars
  2004. def assert_custom_dirty():
  2005. assert mutable_state.dirty_vars == {"_be_custom"}
  2006. mutable_state._clean()
  2007. assert not mutable_state.dirty_vars
  2008. mutable_state._be_custom.foo = "bar"
  2009. assert_custom_dirty()
  2010. mutable_state._be_custom.array.append("baz")
  2011. assert_custom_dirty()
  2012. mutable_state._be_custom.hashmap["key"] = "value"
  2013. assert_custom_dirty()
  2014. mutable_state._be_custom.test_set.add("foo")
  2015. assert_custom_dirty()
  2016. mutable_state._be_custom.custom.bar = "baz"
  2017. assert_custom_dirty()
  2018. @pytest.mark.parametrize(
  2019. ("copy_func",),
  2020. [
  2021. (copy.copy,),
  2022. (copy.deepcopy,),
  2023. ],
  2024. )
  2025. def test_mutable_copy(mutable_state: MutableTestState, copy_func: Callable):
  2026. """Test that mutable types are copied correctly.
  2027. Args:
  2028. mutable_state: A test state.
  2029. copy_func: A copy function.
  2030. """
  2031. ms_copy = copy_func(mutable_state)
  2032. assert ms_copy is not mutable_state
  2033. for attr in ("array", "hashmap", "test_set", "custom"):
  2034. assert getattr(ms_copy, attr) == getattr(mutable_state, attr)
  2035. assert getattr(ms_copy, attr) is not getattr(mutable_state, attr)
  2036. ms_copy.custom.array.append(42)
  2037. assert "custom" in ms_copy.dirty_vars
  2038. if copy_func is copy.copy:
  2039. assert "custom" in mutable_state.dirty_vars
  2040. else:
  2041. assert not mutable_state.dirty_vars
  2042. @pytest.mark.parametrize(
  2043. ("copy_func",),
  2044. [
  2045. (copy.copy,),
  2046. (copy.deepcopy,),
  2047. ],
  2048. )
  2049. def test_mutable_copy_vars(mutable_state: MutableTestState, copy_func: Callable):
  2050. """Test that mutable types are copied correctly.
  2051. Args:
  2052. mutable_state: A test state.
  2053. copy_func: A copy function.
  2054. """
  2055. for attr in ("array", "hashmap", "test_set", "custom"):
  2056. var_orig = getattr(mutable_state, attr)
  2057. var_copy = copy_func(var_orig)
  2058. assert var_orig is not var_copy
  2059. assert var_orig == var_copy
  2060. # copied vars should never be proxies, as they by definition are no longer attached to the state.
  2061. assert not isinstance(var_copy, MutableProxy)
  2062. def test_duplicate_substate_class(mocker):
  2063. # Neuter pytest escape hatch, because we want to test duplicate detection.
  2064. mocker.patch("reflex.state.is_testing_env", lambda: False)
  2065. # Neuter <locals> state handling since these _are_ defined inside a function.
  2066. mocker.patch("reflex.state.BaseState._handle_local_def", lambda: None)
  2067. with pytest.raises(ValueError):
  2068. class TestState(BaseState):
  2069. pass
  2070. class ChildTestState(TestState): # type: ignore # noqa
  2071. pass
  2072. class ChildTestState(TestState): # type: ignore # noqa
  2073. pass
  2074. return TestState
  2075. class Foo(Base):
  2076. """A class containing a list of str."""
  2077. tags: List[str] = ["123", "456"]
  2078. def test_json_dumps_with_mutables():
  2079. """Test that json.dumps works with Base vars inside mutable types."""
  2080. class MutableContainsBase(BaseState):
  2081. items: List[Foo] = [Foo()]
  2082. dict_val = MutableContainsBase().dict()
  2083. assert isinstance(dict_val[MutableContainsBase.get_full_name()]["items"][0], Foo)
  2084. val = json_dumps(dict_val)
  2085. f_items = '[{"tags": ["123", "456"]}]'
  2086. f_formatted_router = str(formatted_router).replace("'", '"')
  2087. assert (
  2088. val
  2089. == f'{{"{MutableContainsBase.get_full_name()}": {{"items": {f_items}, "router": {f_formatted_router}}}}}'
  2090. )
  2091. def test_reset_with_mutables():
  2092. """Calling reset should always reset fields to a copy of the defaults."""
  2093. default = [[0, 0], [0, 1], [1, 1]]
  2094. copied_default = copy.deepcopy(default)
  2095. class MutableResetState(BaseState):
  2096. items: List[List[int]] = default
  2097. instance = MutableResetState()
  2098. assert instance.items.__wrapped__ is not default # type: ignore
  2099. assert instance.items == default == copied_default
  2100. instance.items.append([3, 3])
  2101. assert instance.items != default
  2102. assert instance.items != copied_default
  2103. instance.reset()
  2104. assert instance.items.__wrapped__ is not default # type: ignore
  2105. assert instance.items == default == copied_default
  2106. instance.items.append([3, 3])
  2107. assert instance.items != default
  2108. assert instance.items != copied_default
  2109. instance.reset()
  2110. assert instance.items.__wrapped__ is not default # type: ignore
  2111. assert instance.items == default == copied_default
  2112. instance.items.append([3, 3])
  2113. assert instance.items != default
  2114. assert instance.items != copied_default
  2115. class Custom1(Base):
  2116. """A custom class with a str field."""
  2117. foo: str
  2118. def set_foo(self, val: str):
  2119. """Set the attribute foo.
  2120. Args:
  2121. val: The value to set.
  2122. """
  2123. self.foo = val
  2124. def double_foo(self) -> str:
  2125. """Concantenate foo with foo.
  2126. Returns:
  2127. foo + foo
  2128. """
  2129. return self.foo + self.foo
  2130. class Custom2(Base):
  2131. """A custom class with a Custom1 field."""
  2132. c1: Optional[Custom1] = None
  2133. c1r: Custom1
  2134. def set_c1r_foo(self, val: str):
  2135. """Set the foo attribute of the c1 field.
  2136. Args:
  2137. val: The value to set.
  2138. """
  2139. self.c1r.set_foo(val)
  2140. class Custom3(Base):
  2141. """A custom class with a Custom2 field."""
  2142. c2: Optional[Custom2] = None
  2143. c2r: Custom2
  2144. def test_state_union_optional():
  2145. """Test that state can be defined with Union and Optional vars."""
  2146. class UnionState(BaseState):
  2147. int_float: Union[int, float] = 0
  2148. opt_int: Optional[int]
  2149. c3: Optional[Custom3]
  2150. c3i: Custom3 # implicitly required
  2151. c3r: Custom3 = Custom3(c2r=Custom2(c1r=Custom1(foo="")))
  2152. custom_union: Union[Custom1, Custom2, Custom3] = Custom1(foo="")
  2153. assert str(UnionState.c3.c2) == f'{str(UnionState.c3)}?.["c2"]' # type: ignore
  2154. assert str(UnionState.c3.c2.c1) == f'{str(UnionState.c3)}?.["c2"]?.["c1"]' # type: ignore
  2155. assert (
  2156. str(UnionState.c3.c2.c1.foo) == f'{str(UnionState.c3)}?.["c2"]?.["c1"]?.["foo"]' # type: ignore
  2157. )
  2158. assert (
  2159. str(UnionState.c3.c2.c1r.foo) == f'{str(UnionState.c3)}?.["c2"]?.["c1r"]["foo"]' # type: ignore
  2160. )
  2161. assert str(UnionState.c3.c2r.c1) == f'{str(UnionState.c3)}?.["c2r"]["c1"]' # type: ignore
  2162. assert (
  2163. str(UnionState.c3.c2r.c1.foo) == f'{str(UnionState.c3)}?.["c2r"]["c1"]?.["foo"]' # type: ignore
  2164. )
  2165. assert (
  2166. str(UnionState.c3.c2r.c1r.foo) == f'{str(UnionState.c3)}?.["c2r"]["c1r"]["foo"]' # type: ignore
  2167. )
  2168. assert str(UnionState.c3i.c2) == f'{str(UnionState.c3i)}["c2"]' # type: ignore
  2169. assert str(UnionState.c3r.c2) == f'{str(UnionState.c3r)}["c2"]' # type: ignore
  2170. assert UnionState.custom_union.foo is not None # type: ignore
  2171. assert UnionState.custom_union.c1 is not None # type: ignore
  2172. assert UnionState.custom_union.c1r is not None # type: ignore
  2173. assert UnionState.custom_union.c2 is not None # type: ignore
  2174. assert UnionState.custom_union.c2r is not None # type: ignore
  2175. assert types.is_optional(UnionState.opt_int._var_type) # type: ignore
  2176. assert types.is_union(UnionState.int_float._var_type) # type: ignore
  2177. def test_set_base_field_via_setter():
  2178. """When calling a setter on a Base instance, also track changes."""
  2179. class BaseFieldSetterState(BaseState):
  2180. c1: Custom1 = Custom1(foo="")
  2181. c2: Custom2 = Custom2(c1r=Custom1(foo=""))
  2182. bfss = BaseFieldSetterState()
  2183. assert "c1" not in bfss.dirty_vars
  2184. # Non-mutating function, not dirty
  2185. bfss.c1.double_foo()
  2186. assert "c1" not in bfss.dirty_vars
  2187. # Mutating function, dirty
  2188. bfss.c1.set_foo("bar")
  2189. assert "c1" in bfss.dirty_vars
  2190. bfss.dirty_vars.clear()
  2191. assert "c1" not in bfss.dirty_vars
  2192. # Mutating function from Base, dirty
  2193. bfss.c1.set(foo="bar")
  2194. assert "c1" in bfss.dirty_vars
  2195. bfss.dirty_vars.clear()
  2196. assert "c1" not in bfss.dirty_vars
  2197. # Assert identity of MutableProxy
  2198. mp = bfss.c1
  2199. assert isinstance(mp, MutableProxy)
  2200. mp2 = mp.set()
  2201. assert mp is mp2
  2202. mp3 = bfss.c1.set()
  2203. assert mp is not mp3
  2204. # Since none of these set calls had values, the state should not be dirty
  2205. assert not bfss.dirty_vars
  2206. # Chained Mutating function, dirty
  2207. bfss.c2.set_c1r_foo("baz")
  2208. assert "c2" in bfss.dirty_vars
  2209. def exp_is_hydrated(state: State, is_hydrated: bool = True) -> Dict[str, Any]:
  2210. """Expected IS_HYDRATED delta that would be emitted by HydrateMiddleware.
  2211. Args:
  2212. state: the State that is hydrated.
  2213. is_hydrated: whether the state is hydrated.
  2214. Returns:
  2215. dict similar to that returned by `State.get_delta` with IS_HYDRATED: is_hydrated
  2216. """
  2217. return {state.get_full_name(): {CompileVars.IS_HYDRATED: is_hydrated}}
  2218. class OnLoadState(State):
  2219. """A test state with no return in handler."""
  2220. num: int = 0
  2221. @rx.event
  2222. def test_handler(self):
  2223. """Test handler."""
  2224. self.num += 1
  2225. class OnLoadState2(State):
  2226. """A test state with return in handler."""
  2227. num: int = 0
  2228. name: str
  2229. def test_handler(self):
  2230. """Test handler that calls another handler.
  2231. Returns:
  2232. Chain of EventHandlers
  2233. """
  2234. self.num += 1
  2235. return self.change_name
  2236. def change_name(self):
  2237. """Test handler to change name."""
  2238. self.name = "random"
  2239. class OnLoadState3(State):
  2240. """A test state with async handler."""
  2241. num: int = 0
  2242. async def test_handler(self):
  2243. """Test handler."""
  2244. self.num += 1
  2245. @pytest.mark.asyncio
  2246. @pytest.mark.parametrize(
  2247. "test_state, expected",
  2248. [
  2249. (OnLoadState, {"on_load_state": {"num": 1}}),
  2250. (OnLoadState2, {"on_load_state2": {"num": 1}}),
  2251. (OnLoadState3, {"on_load_state3": {"num": 1}}),
  2252. ],
  2253. )
  2254. async def test_preprocess(app_module_mock, token, test_state, expected, mocker):
  2255. """Test that a state hydrate event is processed correctly.
  2256. Args:
  2257. app_module_mock: The app module that will be returned by get_app().
  2258. token: A token.
  2259. test_state: State to process event.
  2260. expected: Expected delta.
  2261. mocker: pytest mock object.
  2262. """
  2263. mocker.patch(
  2264. "reflex.state.State.class_subclasses", {test_state, OnLoadInternalState}
  2265. )
  2266. app = app_module_mock.app = App(
  2267. state=State, load_events={"index": [test_state.test_handler]}
  2268. )
  2269. state = State()
  2270. updates = []
  2271. async for update in rx.app.process(
  2272. app=app,
  2273. event=Event(
  2274. token=token,
  2275. name=f"{state.get_name()}.{CompileVars.ON_LOAD_INTERNAL}",
  2276. router_data={RouteVar.PATH: "/", RouteVar.ORIGIN: "/", RouteVar.QUERY: {}},
  2277. ),
  2278. sid="sid",
  2279. headers={},
  2280. client_ip="",
  2281. ):
  2282. assert isinstance(update, StateUpdate)
  2283. updates.append(update)
  2284. assert len(updates) == 1
  2285. assert updates[0].delta[State.get_name()].pop("router") is not None
  2286. assert updates[0].delta == exp_is_hydrated(state, False)
  2287. events = updates[0].events
  2288. assert len(events) == 2
  2289. assert (await state._process(events[0]).__anext__()).delta == {
  2290. test_state.get_full_name(): {"num": 1}
  2291. }
  2292. assert (await state._process(events[1]).__anext__()).delta == exp_is_hydrated(state)
  2293. if isinstance(app.state_manager, StateManagerRedis):
  2294. await app.state_manager.close()
  2295. @pytest.mark.asyncio
  2296. async def test_preprocess_multiple_load_events(app_module_mock, token, mocker):
  2297. """Test that a state hydrate event for multiple on-load events is processed correctly.
  2298. Args:
  2299. app_module_mock: The app module that will be returned by get_app().
  2300. token: A token.
  2301. mocker: pytest mock object.
  2302. """
  2303. mocker.patch(
  2304. "reflex.state.State.class_subclasses", {OnLoadState, OnLoadInternalState}
  2305. )
  2306. app = app_module_mock.app = App(
  2307. state=State,
  2308. load_events={"index": [OnLoadState.test_handler, OnLoadState.test_handler]},
  2309. )
  2310. state = State()
  2311. updates = []
  2312. async for update in rx.app.process(
  2313. app=app,
  2314. event=Event(
  2315. token=token,
  2316. name=f"{state.get_full_name()}.{CompileVars.ON_LOAD_INTERNAL}",
  2317. router_data={RouteVar.PATH: "/", RouteVar.ORIGIN: "/", RouteVar.QUERY: {}},
  2318. ),
  2319. sid="sid",
  2320. headers={},
  2321. client_ip="",
  2322. ):
  2323. assert isinstance(update, StateUpdate)
  2324. updates.append(update)
  2325. assert len(updates) == 1
  2326. assert updates[0].delta[State.get_name()].pop("router") is not None
  2327. assert updates[0].delta == exp_is_hydrated(state, False)
  2328. events = updates[0].events
  2329. assert len(events) == 3
  2330. assert (await state._process(events[0]).__anext__()).delta == {
  2331. OnLoadState.get_full_name(): {"num": 1}
  2332. }
  2333. assert (await state._process(events[1]).__anext__()).delta == {
  2334. OnLoadState.get_full_name(): {"num": 2}
  2335. }
  2336. assert (await state._process(events[2]).__anext__()).delta == exp_is_hydrated(state)
  2337. if isinstance(app.state_manager, StateManagerRedis):
  2338. await app.state_manager.close()
  2339. @pytest.mark.asyncio
  2340. async def test_get_state(mock_app: rx.App, token: str):
  2341. """Test that a get_state populates the top level state and delta calculation is correct.
  2342. Args:
  2343. mock_app: An app that will be returned by `get_app()`
  2344. token: A token.
  2345. """
  2346. mock_app.state_manager.state = mock_app.state = TestState
  2347. # Get instance of ChildState2.
  2348. test_state = await mock_app.state_manager.get_state(
  2349. _substate_key(token, ChildState2)
  2350. )
  2351. assert isinstance(test_state, TestState)
  2352. if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
  2353. # All substates are available
  2354. assert tuple(sorted(test_state.substates)) == (
  2355. ChildState.get_name(),
  2356. ChildState2.get_name(),
  2357. ChildState3.get_name(),
  2358. )
  2359. else:
  2360. # Sibling states are only populated if they have computed vars
  2361. assert tuple(sorted(test_state.substates)) == (
  2362. ChildState2.get_name(),
  2363. ChildState3.get_name(),
  2364. )
  2365. # Because ChildState3 has a computed var, it is always dirty, and always populated.
  2366. assert (
  2367. test_state.substates[ChildState3.get_name()]
  2368. .substates[GrandchildState3.get_name()]
  2369. .computed
  2370. == ""
  2371. )
  2372. # Get the child_state2 directly.
  2373. child_state2_direct = test_state.get_substate([ChildState2.get_name()])
  2374. child_state2_get_state = await test_state.get_state(ChildState2)
  2375. # These should be the same object.
  2376. assert child_state2_direct is child_state2_get_state
  2377. # Get arbitrary GrandchildState.
  2378. grandchild_state = await child_state2_get_state.get_state(GrandchildState)
  2379. assert isinstance(grandchild_state, GrandchildState)
  2380. # Now the original root should have all substates populated.
  2381. assert tuple(sorted(test_state.substates)) == (
  2382. ChildState.get_name(),
  2383. ChildState2.get_name(),
  2384. ChildState3.get_name(),
  2385. )
  2386. # ChildState should be retrievable
  2387. child_state_direct = test_state.get_substate([ChildState.get_name()])
  2388. child_state_get_state = await test_state.get_state(ChildState)
  2389. # These should be the same object.
  2390. assert child_state_direct is child_state_get_state
  2391. # GrandchildState instance should be the same as the one retrieved from the child_state2.
  2392. assert grandchild_state is child_state_direct.get_substate(
  2393. [GrandchildState.get_name()]
  2394. )
  2395. grandchild_state.value2 = "set_value"
  2396. assert test_state.get_delta() == {
  2397. TestState.get_full_name(): {
  2398. "sum": 3.14,
  2399. "upper": "",
  2400. },
  2401. GrandchildState.get_full_name(): {
  2402. "value2": "set_value",
  2403. },
  2404. GrandchildState3.get_full_name(): {
  2405. "computed": "",
  2406. },
  2407. }
  2408. # Get a fresh instance
  2409. new_test_state = await mock_app.state_manager.get_state(
  2410. _substate_key(token, ChildState2)
  2411. )
  2412. assert isinstance(new_test_state, TestState)
  2413. if isinstance(mock_app.state_manager, (StateManagerMemory, StateManagerDisk)):
  2414. # In memory, it's the same instance
  2415. assert new_test_state is test_state
  2416. test_state._clean()
  2417. # All substates are available
  2418. assert tuple(sorted(new_test_state.substates)) == (
  2419. ChildState.get_name(),
  2420. ChildState2.get_name(),
  2421. ChildState3.get_name(),
  2422. )
  2423. else:
  2424. # With redis, we get a whole new instance
  2425. assert new_test_state is not test_state
  2426. # Sibling states are only populated if they have computed vars
  2427. assert tuple(sorted(new_test_state.substates)) == (
  2428. ChildState2.get_name(),
  2429. ChildState3.get_name(),
  2430. )
  2431. # Set a value on child_state2, should update cached var in grandchild_state2
  2432. child_state2 = new_test_state.get_substate((ChildState2.get_name(),))
  2433. child_state2.value = "set_c2_value"
  2434. assert new_test_state.get_delta() == {
  2435. TestState.get_full_name(): {
  2436. "sum": 3.14,
  2437. "upper": "",
  2438. },
  2439. ChildState2.get_full_name(): {
  2440. "value": "set_c2_value",
  2441. },
  2442. GrandchildState2.get_full_name(): {
  2443. "cached": "set_c2_value",
  2444. },
  2445. GrandchildState3.get_full_name(): {
  2446. "computed": "",
  2447. },
  2448. }
  2449. @pytest.mark.asyncio
  2450. async def test_get_state_from_sibling_not_cached(mock_app: rx.App, token: str):
  2451. """A test simulating update_vars_internal when setting cookies with computed vars.
  2452. In that case, a sibling state, UpdateVarsInternalState handles the fetching
  2453. of states that need to have values set. Only the states that have a computed
  2454. var are pre-fetched (like Child3 in this test), so `get_state` needs to
  2455. avoid refetching those already-cached states when getting substates,
  2456. otherwise the set values will be overridden by the freshly deserialized
  2457. version and lost.
  2458. Explicit regression test for https://github.com/reflex-dev/reflex/issues/2851.
  2459. Args:
  2460. mock_app: An app that will be returned by `get_app()`
  2461. token: A token.
  2462. """
  2463. class Parent(BaseState):
  2464. """A root state like rx.State."""
  2465. parent_var: int = 0
  2466. class Child(Parent):
  2467. """A state simulating UpdateVarsInternalState."""
  2468. pass
  2469. class Child2(Parent):
  2470. """An unconnected child state."""
  2471. pass
  2472. class Child3(Parent):
  2473. """A child state with a computed var causing it to be pre-fetched.
  2474. If child3_var gets set to a value, and `get_state` erroneously
  2475. re-fetches it from redis, the value will be lost.
  2476. """
  2477. child3_var: int = 0
  2478. @rx.var
  2479. def v(self):
  2480. pass
  2481. class Grandchild3(Child3):
  2482. """An extra layer of substate to catch an issue discovered in
  2483. _determine_missing_parent_states while writing the regression test where
  2484. invalid parent state names were being constructed.
  2485. """
  2486. pass
  2487. class GreatGrandchild3(Grandchild3):
  2488. """Fetching this state wants to also fetch Child3 as a missing parent.
  2489. However, Child3 should already be cached in the state tree because it
  2490. has a computed var.
  2491. """
  2492. pass
  2493. mock_app.state_manager.state = mock_app.state = Parent
  2494. # Get the top level state via unconnected sibling.
  2495. root = await mock_app.state_manager.get_state(_substate_key(token, Child))
  2496. # Set value in parent_var to assert it does not get refetched later.
  2497. root.parent_var = 1
  2498. if isinstance(mock_app.state_manager, StateManagerRedis):
  2499. # When redis is used, only states with computed vars are pre-fetched.
  2500. assert Child2.get_name() not in root.substates
  2501. assert Child3.get_name() in root.substates # (due to @rx.var)
  2502. # Get the unconnected sibling state, which will be used to `get_state` other instances.
  2503. child = root.get_substate(Child.get_full_name().split("."))
  2504. # Get an uncached child state.
  2505. child2 = await child.get_state(Child2)
  2506. assert child2.parent_var == 1
  2507. # Set value on already-cached Child3 state (prefetched because it has a Computed Var).
  2508. child3 = await child.get_state(Child3)
  2509. child3.child3_var = 1
  2510. # Get uncached great_grandchild3 state.
  2511. great_grandchild3 = await child.get_state(GreatGrandchild3)
  2512. # Assert that we didn't re-fetch the parent and child3 state from redis
  2513. assert great_grandchild3.parent_var == 1
  2514. assert great_grandchild3.child3_var == 1
  2515. # Save a reference to the rx.State to shadow the name State for testing.
  2516. RxState = State
  2517. def test_potentially_dirty_substates():
  2518. """Test that potentially_dirty_substates returns the correct substates.
  2519. Even if the name "State" is shadowed, it should still work correctly.
  2520. """
  2521. class State(RxState):
  2522. @computed_var
  2523. def foo(self) -> str:
  2524. return ""
  2525. class C1(State):
  2526. @computed_var
  2527. def bar(self) -> str:
  2528. return ""
  2529. assert RxState._potentially_dirty_substates() == {State}
  2530. assert State._potentially_dirty_substates() == {C1}
  2531. assert C1._potentially_dirty_substates() == set()
  2532. def test_router_var_dep() -> None:
  2533. """Test that router var dependencies are correctly tracked."""
  2534. class RouterVarParentState(State):
  2535. """A parent state for testing router var dependency."""
  2536. pass
  2537. class RouterVarDepState(RouterVarParentState):
  2538. """A state with a router var dependency."""
  2539. @rx.var(cache=True)
  2540. def foo(self) -> str:
  2541. return self.router.page.params.get("foo", "")
  2542. foo = RouterVarDepState.computed_vars["foo"]
  2543. State._init_var_dependency_dicts()
  2544. assert foo._deps(objclass=RouterVarDepState) == {"router"}
  2545. assert RouterVarParentState._potentially_dirty_substates() == {RouterVarDepState}
  2546. assert RouterVarParentState._substate_var_dependencies == {
  2547. "router": {RouterVarDepState.get_name()}
  2548. }
  2549. assert RouterVarDepState._computed_var_dependencies == {
  2550. "router": {"foo"},
  2551. }
  2552. rx_state = State()
  2553. parent_state = RouterVarParentState()
  2554. state = RouterVarDepState()
  2555. # link states
  2556. rx_state.substates = {RouterVarParentState.get_name(): parent_state}
  2557. parent_state.parent_state = rx_state
  2558. state.parent_state = parent_state
  2559. parent_state.substates = {RouterVarDepState.get_name(): state}
  2560. assert state.dirty_vars == set()
  2561. # Reassign router var
  2562. state.router = state.router
  2563. assert state.dirty_vars == {"foo", "router"}
  2564. assert parent_state.dirty_substates == {RouterVarDepState.get_name()}
  2565. @pytest.mark.asyncio
  2566. async def test_setvar(mock_app: rx.App, token: str):
  2567. """Test that setvar works correctly.
  2568. Args:
  2569. mock_app: An app that will be returned by `get_app()`
  2570. token: A token.
  2571. """
  2572. state = await mock_app.state_manager.get_state(_substate_key(token, TestState))
  2573. # Set Var in same state (with Var type casting)
  2574. for event in rx.event.fix_events(
  2575. [TestState.setvar("num1", 42), TestState.setvar("num2", "4.2")], token
  2576. ):
  2577. async for update in state._process(event):
  2578. print(update)
  2579. assert state.num1 == 42
  2580. assert state.num2 == 4.2
  2581. # Set Var in parent state
  2582. for event in rx.event.fix_events([GrandchildState.setvar("array", [43])], token):
  2583. async for update in state._process(event):
  2584. print(update)
  2585. assert state.array == [43]
  2586. # Cannot setvar for non-existant var
  2587. with pytest.raises(AttributeError):
  2588. TestState.setvar("non_existant_var")
  2589. # Cannot setvar for computed vars
  2590. with pytest.raises(AttributeError):
  2591. TestState.setvar("sum")
  2592. # Cannot setvar with non-string
  2593. with pytest.raises(ValueError):
  2594. TestState.setvar(42, 42)
  2595. @pytest.mark.asyncio
  2596. async def test_setvar_async_setter():
  2597. """Test that overridden async setters raise Exception when used with setvar."""
  2598. with pytest.raises(NotImplementedError):
  2599. TestState.setvar("asynctest", 42)
  2600. @pytest.mark.skipif("REDIS_URL" not in os.environ, reason="Test requires redis")
  2601. @pytest.mark.parametrize(
  2602. "expiration_kwargs, expected_values",
  2603. [
  2604. ({"redis_lock_expiration": 20000}, (20000, constants.Expiration.TOKEN)),
  2605. (
  2606. {"redis_lock_expiration": 50000, "redis_token_expiration": 5600},
  2607. (50000, 5600),
  2608. ),
  2609. ({"redis_token_expiration": 7600}, (constants.Expiration.LOCK, 7600)),
  2610. ],
  2611. )
  2612. def test_redis_state_manager_config_knobs(tmp_path, expiration_kwargs, expected_values):
  2613. proj_root = tmp_path / "project1"
  2614. proj_root.mkdir()
  2615. config_items = ",\n ".join(
  2616. f"{key} = {value}" for key, value in expiration_kwargs.items()
  2617. )
  2618. config_string = f"""
  2619. import reflex as rx
  2620. config = rx.Config(
  2621. app_name="project1",
  2622. redis_url="redis://localhost:6379",
  2623. state_manager_mode="redis",
  2624. {config_items}
  2625. )
  2626. """
  2627. (proj_root / "rxconfig.py").write_text(dedent(config_string))
  2628. with chdir(proj_root):
  2629. # reload config for each parameter to avoid stale values
  2630. reflex.config.get_config(reload=True)
  2631. from reflex.state import State, StateManager
  2632. state_manager = StateManager.create(state=State)
  2633. assert state_manager.lock_expiration == expected_values[0] # type: ignore
  2634. assert state_manager.token_expiration == expected_values[1] # type: ignore
  2635. class MixinState(State, mixin=True):
  2636. """A mixin state for testing."""
  2637. num: int = 0
  2638. _backend: int = 0
  2639. _backend_no_default: dict
  2640. @rx.var(cache=True)
  2641. def computed(self) -> str:
  2642. """A computed var on mixin state.
  2643. Returns:
  2644. A computed value.
  2645. """
  2646. return ""
  2647. class UsesMixinState(MixinState, State):
  2648. """A state that uses the mixin state."""
  2649. pass
  2650. class ChildUsesMixinState(UsesMixinState):
  2651. """A child state that uses the mixin state."""
  2652. pass
  2653. def test_mixin_state() -> None:
  2654. """Test that a mixin state works correctly."""
  2655. assert "num" in UsesMixinState.base_vars
  2656. assert "num" in UsesMixinState.vars
  2657. assert UsesMixinState.backend_vars == {"_backend": 0, "_backend_no_default": {}}
  2658. assert "computed" in UsesMixinState.computed_vars
  2659. assert "computed" in UsesMixinState.vars
  2660. assert (
  2661. UsesMixinState(_reflex_internal_init=True)._backend_no_default # type: ignore
  2662. is not UsesMixinState.backend_vars["_backend_no_default"]
  2663. )
  2664. def test_child_mixin_state() -> None:
  2665. """Test that mixin vars are only applied to the highest state in the hierarchy."""
  2666. assert "num" in ChildUsesMixinState.inherited_vars
  2667. assert "num" not in ChildUsesMixinState.base_vars
  2668. assert "computed" in ChildUsesMixinState.inherited_vars
  2669. assert "computed" not in ChildUsesMixinState.computed_vars
  2670. def test_assignment_to_undeclared_vars():
  2671. """Test that an attribute error is thrown when undeclared vars are set."""
  2672. class State(BaseState):
  2673. val: str
  2674. _val: str
  2675. __val: str # type: ignore
  2676. def handle_supported_regular_vars(self):
  2677. self.val = "no underscore"
  2678. self._val = "single leading underscore"
  2679. self.__val = "double leading undercore"
  2680. def handle_regular_var(self):
  2681. self.num = 5
  2682. def handle_backend_var(self):
  2683. self._num = 5
  2684. def handle_non_var(self):
  2685. self.__num = 5
  2686. class Substate(State):
  2687. def handle_var(self):
  2688. self.value = 20
  2689. state = State() # type: ignore
  2690. sub_state = Substate() # type: ignore
  2691. with pytest.raises(SetUndefinedStateVarError):
  2692. state.handle_regular_var()
  2693. with pytest.raises(SetUndefinedStateVarError):
  2694. sub_state.handle_var()
  2695. with pytest.raises(SetUndefinedStateVarError):
  2696. state.handle_backend_var()
  2697. state.handle_supported_regular_vars()
  2698. state.handle_non_var()
  2699. @pytest.mark.asyncio
  2700. async def test_deserialize_gc_state_disk(token):
  2701. """Test that a state can be deserialized from disk with a grandchild state.
  2702. Args:
  2703. token: A token.
  2704. """
  2705. class Root(BaseState):
  2706. pass
  2707. class State(Root):
  2708. num: int = 42
  2709. class Child(State):
  2710. foo: str = "bar"
  2711. dsm = StateManagerDisk(state=Root)
  2712. async with dsm.modify_state(token) as root:
  2713. s = await root.get_state(State)
  2714. s.num += 1
  2715. c = await root.get_state(Child)
  2716. assert s._get_was_touched()
  2717. assert not c._get_was_touched()
  2718. dsm2 = StateManagerDisk(state=Root)
  2719. root = await dsm2.get_state(token)
  2720. s = await root.get_state(State)
  2721. assert s.num == 43
  2722. c = await root.get_state(Child)
  2723. assert c.foo == "bar"
  2724. class Obj(Base):
  2725. """A object containing a callable for testing fallback pickle."""
  2726. _f: Callable
  2727. def test_fallback_pickle():
  2728. """Test that state serialization will fall back to dill."""
  2729. class DillState(BaseState):
  2730. _o: Optional[Obj] = None
  2731. _f: Optional[Callable] = None
  2732. _g: Any = None
  2733. state = DillState(_reflex_internal_init=True) # type: ignore
  2734. state._o = Obj(_f=lambda: 42)
  2735. state._f = lambda: 420
  2736. pk = state._serialize()
  2737. unpickled_state = BaseState._deserialize(pk)
  2738. assert unpickled_state._f() == 420
  2739. assert unpickled_state._o._f() == 42
  2740. # Threading locks are unpicklable normally, and raise TypeError instead of PicklingError.
  2741. state2 = DillState(_reflex_internal_init=True) # type: ignore
  2742. state2._g = threading.Lock()
  2743. pk2 = state2._serialize()
  2744. unpickled_state2 = BaseState._deserialize(pk2)
  2745. assert isinstance(unpickled_state2._g, type(threading.Lock()))
  2746. # Some object, like generator, are still unpicklable with dill.
  2747. state3 = DillState(_reflex_internal_init=True) # type: ignore
  2748. state3._g = (i for i in range(10))
  2749. pk3 = state3._serialize()
  2750. assert len(pk3) == 0
  2751. def test_typed_state() -> None:
  2752. class TypedState(rx.State):
  2753. field: rx.Field[str] = rx.field("")
  2754. _ = TypedState(field="str")
  2755. class ModelV1(BaseModelV1):
  2756. """A pydantic BaseModel v1."""
  2757. foo: str = "bar"
  2758. class ModelV2(BaseModelV2):
  2759. """A pydantic BaseModel v2."""
  2760. foo: str = "bar"
  2761. @dataclasses.dataclass
  2762. class ModelDC:
  2763. """A dataclass."""
  2764. foo: str = "bar"
  2765. class PydanticState(rx.State):
  2766. """A state with pydantic BaseModel vars."""
  2767. v1: ModelV1 = ModelV1()
  2768. v2: ModelV2 = ModelV2()
  2769. dc: ModelDC = ModelDC()
  2770. def test_mutable_models():
  2771. """Test that dataclass and pydantic BaseModel v1 and v2 use dep tracking."""
  2772. state = PydanticState()
  2773. assert isinstance(state.v1, MutableProxy)
  2774. state.v1.foo = "baz"
  2775. assert state.dirty_vars == {"v1"}
  2776. state.dirty_vars.clear()
  2777. assert isinstance(state.v2, MutableProxy)
  2778. state.v2.foo = "baz"
  2779. assert state.dirty_vars == {"v2"}
  2780. state.dirty_vars.clear()
  2781. # Not yet supported ENG-4083
  2782. # assert isinstance(state.dc, MutableProxy)
  2783. # state.dc.foo = "baz"
  2784. # assert state.dirty_vars == {"dc"}
  2785. # state.dirty_vars.clear()
  2786. def test_get_value():
  2787. class GetValueState(rx.State):
  2788. foo: str = "FOO"
  2789. bar: str = "BAR"
  2790. state = GetValueState()
  2791. assert state.dict() == {
  2792. state.get_full_name(): {
  2793. "foo": "FOO",
  2794. "bar": "BAR",
  2795. }
  2796. }
  2797. assert state.get_delta() == {}
  2798. state.bar = "foo"
  2799. assert state.dict() == {
  2800. state.get_full_name(): {
  2801. "foo": "FOO",
  2802. "bar": "foo",
  2803. }
  2804. }
  2805. assert state.get_delta() == {
  2806. state.get_full_name(): {
  2807. "bar": "foo",
  2808. }
  2809. }
  2810. def test_init_mixin() -> None:
  2811. """Ensure that State mixins can not be instantiated directly."""
  2812. class Mixin(BaseState, mixin=True):
  2813. pass
  2814. with pytest.raises(ReflexRuntimeError):
  2815. Mixin()
  2816. class SubMixin(Mixin, mixin=True):
  2817. pass
  2818. with pytest.raises(ReflexRuntimeError):
  2819. SubMixin()
  2820. class ReflexModel(rx.Model):
  2821. """A model for testing."""
  2822. foo: str
  2823. class UpcastState(rx.State):
  2824. """A state for testing upcasting."""
  2825. passed: bool = False
  2826. def rx_model(self, m: ReflexModel): # noqa: D102
  2827. assert isinstance(m, ReflexModel)
  2828. self.passed = True
  2829. def rx_base(self, o: Object): # noqa: D102
  2830. assert isinstance(o, Object)
  2831. self.passed = True
  2832. def rx_base_or_none(self, o: Optional[Object]): # noqa: D102
  2833. if o is not None:
  2834. assert isinstance(o, Object)
  2835. self.passed = True
  2836. def rx_basemodelv1(self, m: ModelV1): # noqa: D102
  2837. assert isinstance(m, ModelV1)
  2838. self.passed = True
  2839. def rx_basemodelv2(self, m: ModelV2): # noqa: D102
  2840. assert isinstance(m, ModelV2)
  2841. self.passed = True
  2842. def rx_dataclass(self, dc: ModelDC): # noqa: D102
  2843. assert isinstance(dc, ModelDC)
  2844. self.passed = True
  2845. def py_set(self, s: set): # noqa: D102
  2846. assert isinstance(s, set)
  2847. self.passed = True
  2848. def py_Set(self, s: Set): # noqa: D102
  2849. assert isinstance(s, Set)
  2850. self.passed = True
  2851. def py_tuple(self, t: tuple): # noqa: D102
  2852. assert isinstance(t, tuple)
  2853. self.passed = True
  2854. def py_Tuple(self, t: Tuple): # noqa: D102
  2855. assert isinstance(t, tuple)
  2856. self.passed = True
  2857. def py_dict(self, d: dict[str, str]): # noqa: D102
  2858. assert isinstance(d, dict)
  2859. self.passed = True
  2860. def py_list(self, ls: list[str]): # noqa: D102
  2861. assert isinstance(ls, list)
  2862. self.passed = True
  2863. def py_Any(self, a: Any): # noqa: D102
  2864. assert isinstance(a, list)
  2865. self.passed = True
  2866. def py_unresolvable(self, u: "Unresolvable"): # noqa: D102, F821 # type: ignore
  2867. assert isinstance(u, list)
  2868. self.passed = True
  2869. @pytest.mark.asyncio
  2870. @pytest.mark.usefixtures("mock_app_simple")
  2871. @pytest.mark.parametrize(
  2872. ("handler", "payload"),
  2873. [
  2874. (UpcastState.rx_model, {"m": {"foo": "bar"}}),
  2875. (UpcastState.rx_base, {"o": {"foo": "bar"}}),
  2876. (UpcastState.rx_base_or_none, {"o": {"foo": "bar"}}),
  2877. (UpcastState.rx_base_or_none, {"o": None}),
  2878. (UpcastState.rx_basemodelv1, {"m": {"foo": "bar"}}),
  2879. (UpcastState.rx_basemodelv2, {"m": {"foo": "bar"}}),
  2880. (UpcastState.rx_dataclass, {"dc": {"foo": "bar"}}),
  2881. (UpcastState.py_set, {"s": ["foo", "foo"]}),
  2882. (UpcastState.py_Set, {"s": ["foo", "foo"]}),
  2883. (UpcastState.py_tuple, {"t": ["foo", "foo"]}),
  2884. (UpcastState.py_Tuple, {"t": ["foo", "foo"]}),
  2885. (UpcastState.py_dict, {"d": {"foo": "bar"}}),
  2886. (UpcastState.py_list, {"ls": ["foo", "foo"]}),
  2887. (UpcastState.py_Any, {"a": ["foo"]}),
  2888. (UpcastState.py_unresolvable, {"u": ["foo"]}),
  2889. ],
  2890. )
  2891. async def test_upcast_event_handler_arg(handler, payload):
  2892. """Test that upcast event handler args work correctly.
  2893. Args:
  2894. handler: The handler to test.
  2895. payload: The payload to test.
  2896. """
  2897. state = UpcastState()
  2898. async for update in state._process_event(handler, state, payload):
  2899. assert update.delta == {UpcastState.get_full_name(): {"passed": True}}