test_state.py 123 KB

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