test_state.py 107 KB

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