test_state.py 95 KB

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