test_state.py 111 KB

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