test_state.py 97 KB

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