test_state.py 93 KB

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