test_state.py 88 KB

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