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