1
0

test_state.py 118 KB

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