test_state.py 122 KB

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