test_state.py 118 KB

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