test_state.py 100 KB

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