test_state.py 107 KB

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