test_state.py 107 KB

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