test_state.py 97 KB

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