1
0

test_state.py 119 KB

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