test_state.py 113 KB

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