test_state.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971
  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.cached_var
  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.cached_var
  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.cached_var
  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.cached_var
  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.cached_var
  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.cached_var
  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.cached_var
  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.cached_var
  909. def dep_v(self) -> int:
  910. return self.no_cache_v # type: ignore
  911. @rx.cached_var
  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.cached_var
  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.cached_var
  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. @rx.cached_var
  1009. def comp_v(self) -> int:
  1010. """Direct access.
  1011. Returns:
  1012. The value of self.v.
  1013. """
  1014. return self.v
  1015. @rx.cached_var
  1016. def comp_w(self):
  1017. """Nested lambda.
  1018. Returns:
  1019. A lambda that returns the value of self.w.
  1020. """
  1021. return lambda: self.w
  1022. @rx.cached_var
  1023. def comp_x(self):
  1024. """Nested function.
  1025. Returns:
  1026. A function that returns the value of self.x.
  1027. """
  1028. def _():
  1029. return self.x
  1030. return _
  1031. @rx.cached_var
  1032. def comp_y(self) -> List[int]:
  1033. """Comprehension iterating over attribute.
  1034. Returns:
  1035. A list of the values of self.y.
  1036. """
  1037. return [round(y) for y in self.y]
  1038. @rx.cached_var
  1039. def comp_z(self) -> List[bool]:
  1040. """Comprehension accesses attribute.
  1041. Returns:
  1042. A list of whether the values 0-4 are in self._z.
  1043. """
  1044. return [z in self._z for z in range(5)]
  1045. cs = ComputedState()
  1046. assert cs._computed_var_dependencies["v"] == {"comp_v"}
  1047. assert cs._computed_var_dependencies["w"] == {"comp_w"}
  1048. assert cs._computed_var_dependencies["x"] == {"comp_x"}
  1049. assert cs._computed_var_dependencies["y"] == {"comp_y"}
  1050. assert cs._computed_var_dependencies["_z"] == {"comp_z"}
  1051. def test_backend_method():
  1052. """A method with leading underscore should be callable from event handler."""
  1053. class BackendMethodState(BaseState):
  1054. def _be_method(self):
  1055. return True
  1056. def handler(self):
  1057. assert self._be_method()
  1058. bms = BackendMethodState()
  1059. bms.handler()
  1060. assert bms._be_method()
  1061. def test_setattr_of_mutable_types(mutable_state):
  1062. """Test that mutable types are converted to corresponding Reflex wrappers.
  1063. Args:
  1064. mutable_state: A test state.
  1065. """
  1066. array = mutable_state.array
  1067. hashmap = mutable_state.hashmap
  1068. test_set = mutable_state.test_set
  1069. assert isinstance(array, MutableProxy)
  1070. assert isinstance(array, list)
  1071. assert isinstance(array[1], MutableProxy)
  1072. assert isinstance(array[1], list)
  1073. assert isinstance(array[2], MutableProxy)
  1074. assert isinstance(array[2], dict)
  1075. assert isinstance(hashmap, MutableProxy)
  1076. assert isinstance(hashmap, dict)
  1077. assert isinstance(hashmap["key"], MutableProxy)
  1078. assert isinstance(hashmap["key"], list)
  1079. assert isinstance(hashmap["third_key"], MutableProxy)
  1080. assert isinstance(hashmap["third_key"], dict)
  1081. assert isinstance(test_set, MutableProxy)
  1082. assert isinstance(test_set, set)
  1083. assert isinstance(mutable_state.custom, MutableProxy)
  1084. assert isinstance(mutable_state.custom.array, MutableProxy)
  1085. assert isinstance(mutable_state.custom.array, list)
  1086. assert isinstance(mutable_state.custom.hashmap, MutableProxy)
  1087. assert isinstance(mutable_state.custom.hashmap, dict)
  1088. assert isinstance(mutable_state.custom.test_set, MutableProxy)
  1089. assert isinstance(mutable_state.custom.test_set, set)
  1090. assert isinstance(mutable_state.custom.custom, MutableProxy)
  1091. mutable_state.reassign_mutables()
  1092. array = mutable_state.array
  1093. hashmap = mutable_state.hashmap
  1094. test_set = mutable_state.test_set
  1095. assert isinstance(array, MutableProxy)
  1096. assert isinstance(array, list)
  1097. assert isinstance(array[1], MutableProxy)
  1098. assert isinstance(array[1], list)
  1099. assert isinstance(array[2], MutableProxy)
  1100. assert isinstance(array[2], dict)
  1101. assert isinstance(hashmap, MutableProxy)
  1102. assert isinstance(hashmap, dict)
  1103. assert isinstance(hashmap["mod_key"], MutableProxy)
  1104. assert isinstance(hashmap["mod_key"], list)
  1105. assert isinstance(hashmap["mod_third_key"], MutableProxy)
  1106. assert isinstance(hashmap["mod_third_key"], dict)
  1107. assert isinstance(test_set, MutableProxy)
  1108. assert isinstance(test_set, set)
  1109. def test_error_on_state_method_shadow():
  1110. """Test that an error is thrown when an event handler shadows a state method."""
  1111. with pytest.raises(NameError) as err:
  1112. class InvalidTest(BaseState):
  1113. def reset(self):
  1114. pass
  1115. assert (
  1116. err.value.args[0]
  1117. == f"The event handler name `reset` shadows a builtin State method; use a different name instead"
  1118. )
  1119. @pytest.mark.asyncio
  1120. async def test_state_with_invalid_yield(capsys):
  1121. """Test that an error is thrown when a state yields an invalid value.
  1122. Args:
  1123. capsys: Pytest fixture for capture standard streams.
  1124. """
  1125. class StateWithInvalidYield(BaseState):
  1126. """A state that yields an invalid value."""
  1127. def invalid_handler(self):
  1128. """Invalid handler.
  1129. Yields:
  1130. an invalid value.
  1131. """
  1132. yield 1
  1133. invalid_state = StateWithInvalidYield()
  1134. async for update in invalid_state._process(
  1135. rx.event.Event(token="fake_token", name="invalid_handler")
  1136. ):
  1137. assert not update.delta
  1138. assert update.events == rx.event.fix_events(
  1139. [rx.window_alert("An error occurred. See logs for details.")],
  1140. token="",
  1141. )
  1142. captured = capsys.readouterr()
  1143. assert "must only return/yield: None, Events or other EventHandlers" in captured.out
  1144. @pytest.fixture(scope="function", params=["in_process", "redis"])
  1145. def state_manager(request) -> Generator[StateManager, None, None]:
  1146. """Instance of state manager parametrized for redis and in-process.
  1147. Args:
  1148. request: pytest request object.
  1149. Yields:
  1150. A state manager instance
  1151. """
  1152. state_manager = StateManager.create(state=TestState)
  1153. if request.param == "redis":
  1154. if not isinstance(state_manager, StateManagerRedis):
  1155. pytest.skip("Test requires redis")
  1156. else:
  1157. # explicitly NOT using redis
  1158. state_manager = StateManagerMemory(state=TestState)
  1159. assert not state_manager._states_locks
  1160. yield state_manager
  1161. if isinstance(state_manager, StateManagerRedis):
  1162. asyncio.get_event_loop().run_until_complete(state_manager.close())
  1163. @pytest.fixture()
  1164. def substate_token(state_manager, token):
  1165. """A token + substate name for looking up in state manager.
  1166. Args:
  1167. state_manager: A state manager instance.
  1168. token: A token.
  1169. Returns:
  1170. Token concatenated with the state_manager's state full_name.
  1171. """
  1172. return _substate_key(token, state_manager.state)
  1173. @pytest.mark.asyncio
  1174. async def test_state_manager_modify_state(
  1175. state_manager: StateManager, token: str, substate_token: str
  1176. ):
  1177. """Test that the state manager can modify a state exclusively.
  1178. Args:
  1179. state_manager: A state manager instance.
  1180. token: A token.
  1181. substate_token: A token + substate name for looking up in state manager.
  1182. """
  1183. async with state_manager.modify_state(substate_token) as state:
  1184. if isinstance(state_manager, StateManagerRedis):
  1185. assert await state_manager.redis.get(f"{token}_lock")
  1186. elif isinstance(state_manager, StateManagerMemory):
  1187. assert token in state_manager._states_locks
  1188. assert state_manager._states_locks[token].locked()
  1189. # Should be able to write proxy objects inside mutables
  1190. complex_1 = state.complex[1]
  1191. assert isinstance(complex_1, MutableProxy)
  1192. state.complex[3] = complex_1
  1193. # lock should be dropped after exiting the context
  1194. if isinstance(state_manager, StateManagerRedis):
  1195. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1196. elif isinstance(state_manager, StateManagerMemory):
  1197. assert not state_manager._states_locks[token].locked()
  1198. # separate instances should NOT share locks
  1199. sm2 = StateManagerMemory(state=TestState)
  1200. assert sm2._state_manager_lock is state_manager._state_manager_lock
  1201. assert not sm2._states_locks
  1202. if state_manager._states_locks:
  1203. assert sm2._states_locks != state_manager._states_locks
  1204. @pytest.mark.asyncio
  1205. async def test_state_manager_contend(
  1206. state_manager: StateManager, token: str, substate_token: str
  1207. ):
  1208. """Multiple coroutines attempting to access the same state.
  1209. Args:
  1210. state_manager: A state manager instance.
  1211. token: A token.
  1212. substate_token: A token + substate name for looking up in state manager.
  1213. """
  1214. n_coroutines = 10
  1215. exp_num1 = 10
  1216. async with state_manager.modify_state(substate_token) as state:
  1217. state.num1 = 0
  1218. async def _coro():
  1219. async with state_manager.modify_state(substate_token) as state:
  1220. await asyncio.sleep(0.01)
  1221. state.num1 += 1
  1222. tasks = [asyncio.create_task(_coro()) for _ in range(n_coroutines)]
  1223. for f in asyncio.as_completed(tasks):
  1224. await f
  1225. assert (await state_manager.get_state(substate_token)).num1 == exp_num1
  1226. if isinstance(state_manager, StateManagerRedis):
  1227. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1228. elif isinstance(state_manager, StateManagerMemory):
  1229. assert token in state_manager._states_locks
  1230. assert not state_manager._states_locks[token].locked()
  1231. @pytest.fixture(scope="function")
  1232. def state_manager_redis() -> Generator[StateManager, None, None]:
  1233. """Instance of state manager for redis only.
  1234. Yields:
  1235. A state manager instance
  1236. """
  1237. state_manager = StateManager.create(TestState)
  1238. if not isinstance(state_manager, StateManagerRedis):
  1239. pytest.skip("Test requires redis")
  1240. yield state_manager
  1241. asyncio.get_event_loop().run_until_complete(state_manager.close())
  1242. @pytest.fixture()
  1243. def substate_token_redis(state_manager_redis, token):
  1244. """A token + substate name for looking up in state manager.
  1245. Args:
  1246. state_manager_redis: A state manager instance.
  1247. token: A token.
  1248. Returns:
  1249. Token concatenated with the state_manager's state full_name.
  1250. """
  1251. return _substate_key(token, state_manager_redis.state)
  1252. @pytest.mark.asyncio
  1253. async def test_state_manager_lock_expire(
  1254. state_manager_redis: StateManager, token: str, substate_token_redis: str
  1255. ):
  1256. """Test that the state manager lock expires and raises exception exiting context.
  1257. Args:
  1258. state_manager_redis: A state manager instance.
  1259. token: A token.
  1260. substate_token_redis: A token + substate name for looking up in state manager.
  1261. """
  1262. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1263. async with state_manager_redis.modify_state(substate_token_redis):
  1264. await asyncio.sleep(0.01)
  1265. with pytest.raises(LockExpiredError):
  1266. async with state_manager_redis.modify_state(substate_token_redis):
  1267. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1268. @pytest.mark.asyncio
  1269. async def test_state_manager_lock_expire_contend(
  1270. state_manager_redis: StateManager, token: str, substate_token_redis: str
  1271. ):
  1272. """Test that the state manager lock expires and queued waiters proceed.
  1273. Args:
  1274. state_manager_redis: A state manager instance.
  1275. token: A token.
  1276. substate_token_redis: A token + substate name for looking up in state manager.
  1277. """
  1278. exp_num1 = 4252
  1279. unexp_num1 = 666
  1280. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1281. order = []
  1282. async def _coro_blocker():
  1283. async with state_manager_redis.modify_state(substate_token_redis) as state:
  1284. order.append("blocker")
  1285. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1286. state.num1 = unexp_num1
  1287. async def _coro_waiter():
  1288. while "blocker" not in order:
  1289. await asyncio.sleep(0.005)
  1290. async with state_manager_redis.modify_state(substate_token_redis) as state:
  1291. order.append("waiter")
  1292. assert state.num1 != unexp_num1
  1293. state.num1 = exp_num1
  1294. tasks = [
  1295. asyncio.create_task(_coro_blocker()),
  1296. asyncio.create_task(_coro_waiter()),
  1297. ]
  1298. with pytest.raises(LockExpiredError):
  1299. await tasks[0]
  1300. await tasks[1]
  1301. assert order == ["blocker", "waiter"]
  1302. assert (await state_manager_redis.get_state(substate_token_redis)).num1 == exp_num1
  1303. @pytest.fixture(scope="function")
  1304. def mock_app(monkeypatch, state_manager: StateManager) -> rx.App:
  1305. """Mock app fixture.
  1306. Args:
  1307. monkeypatch: Pytest monkeypatch object.
  1308. state_manager: A state manager.
  1309. Returns:
  1310. The app, after mocking out prerequisites.get_app()
  1311. """
  1312. app = App(state=TestState)
  1313. app_module = Mock()
  1314. setattr(app_module, CompileVars.APP, app)
  1315. app.state = TestState
  1316. app._state_manager = state_manager
  1317. app.event_namespace.emit = AsyncMock() # type: ignore
  1318. def _mock_get_app(*args, **kwargs):
  1319. return app_module
  1320. monkeypatch.setattr(prerequisites, "get_app", _mock_get_app)
  1321. return app
  1322. @pytest.mark.asyncio
  1323. async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
  1324. """Test that the state proxy works.
  1325. Args:
  1326. grandchild_state: A grandchild state.
  1327. mock_app: An app that will be returned by `get_app()`
  1328. """
  1329. child_state = grandchild_state.parent_state
  1330. assert child_state is not None
  1331. parent_state = child_state.parent_state
  1332. assert parent_state is not None
  1333. if isinstance(mock_app.state_manager, StateManagerMemory):
  1334. mock_app.state_manager.states[parent_state.router.session.client_token] = (
  1335. parent_state
  1336. )
  1337. sp = StateProxy(grandchild_state)
  1338. assert sp.__wrapped__ == grandchild_state
  1339. assert sp._self_substate_path == grandchild_state.get_full_name().split(".")
  1340. assert sp._self_app is mock_app
  1341. assert not sp._self_mutable
  1342. assert sp._self_actx is None
  1343. # cannot use normal contextmanager protocol
  1344. with pytest.raises(TypeError), sp:
  1345. pass
  1346. with pytest.raises(ImmutableStateError):
  1347. # cannot directly modify state proxy outside of async context
  1348. sp.value2 = "16"
  1349. with pytest.raises(ImmutableStateError):
  1350. # Cannot get_state
  1351. await sp.get_state(ChildState)
  1352. with pytest.raises(ImmutableStateError):
  1353. # Cannot access get_substate
  1354. sp.get_substate([])
  1355. with pytest.raises(ImmutableStateError):
  1356. # Cannot access parent state
  1357. sp.parent_state.get_name()
  1358. with pytest.raises(ImmutableStateError):
  1359. # Cannot access substates
  1360. sp.substates[""]
  1361. async with sp:
  1362. assert sp._self_actx is not None
  1363. assert sp._self_mutable # proxy is mutable inside context
  1364. if isinstance(mock_app.state_manager, StateManagerMemory):
  1365. # For in-process store, only one instance of the state exists
  1366. assert sp.__wrapped__ is grandchild_state
  1367. else:
  1368. # When redis is used, a new+updated instance is assigned to the proxy
  1369. assert sp.__wrapped__ is not grandchild_state
  1370. sp.value2 = "42"
  1371. assert not sp._self_mutable # proxy is not mutable after exiting context
  1372. assert sp._self_actx is None
  1373. assert sp.value2 == "42"
  1374. # Get the state from the state manager directly and check that the value is updated
  1375. gotten_state = await mock_app.state_manager.get_state(
  1376. _substate_key(grandchild_state.router.session.client_token, grandchild_state)
  1377. )
  1378. if isinstance(mock_app.state_manager, StateManagerMemory):
  1379. # For in-process store, only one instance of the state exists
  1380. assert gotten_state is parent_state
  1381. else:
  1382. assert gotten_state is not parent_state
  1383. gotten_grandchild_state = gotten_state.get_substate(sp._self_substate_path)
  1384. assert gotten_grandchild_state is not None
  1385. assert gotten_grandchild_state.value2 == "42"
  1386. # ensure state update was emitted
  1387. assert mock_app.event_namespace is not None
  1388. mock_app.event_namespace.emit.assert_called_once()
  1389. mcall = mock_app.event_namespace.emit.mock_calls[0]
  1390. assert mcall.args[0] == str(SocketEvent.EVENT)
  1391. assert json.loads(mcall.args[1]) == StateUpdate(
  1392. delta={
  1393. parent_state.get_full_name(): {
  1394. "upper": "",
  1395. "sum": 3.14,
  1396. },
  1397. grandchild_state.get_full_name(): {
  1398. "value2": "42",
  1399. },
  1400. GrandchildState3.get_full_name(): {
  1401. "computed": "",
  1402. },
  1403. }
  1404. )
  1405. assert mcall.kwargs["to"] == grandchild_state.router.session.session_id
  1406. class BackgroundTaskState(BaseState):
  1407. """A state with a background task."""
  1408. order: List[str] = []
  1409. dict_list: Dict[str, List[int]] = {"foo": [1, 2, 3]}
  1410. @rx.var
  1411. def computed_order(self) -> List[str]:
  1412. """Get the order as a computed var.
  1413. Returns:
  1414. The value of 'order' var.
  1415. """
  1416. return self.order
  1417. @rx.background
  1418. async def background_task(self):
  1419. """A background task that updates the state."""
  1420. async with self:
  1421. assert not self.order
  1422. self.order.append("background_task:start")
  1423. assert isinstance(self, StateProxy)
  1424. with pytest.raises(ImmutableStateError):
  1425. self.order.append("bad idea")
  1426. with pytest.raises(ImmutableStateError):
  1427. # Even nested access to mutables raises an exception.
  1428. self.dict_list["foo"].append(42)
  1429. with pytest.raises(ImmutableStateError):
  1430. # Direct calling another handler that modifies state raises an exception.
  1431. self.other()
  1432. with pytest.raises(ImmutableStateError):
  1433. # Calling other methods that modify state raises an exception.
  1434. self._private_method()
  1435. # wait for some other event to happen
  1436. while len(self.order) == 1:
  1437. await asyncio.sleep(0.01)
  1438. async with self:
  1439. pass # update proxy instance
  1440. async with self:
  1441. # Methods on ImmutableMutableProxy should return their wrapped return value.
  1442. assert self.dict_list.pop("foo") == [1, 2, 3]
  1443. self.order.append("background_task:stop")
  1444. self.other() # direct calling event handlers works in context
  1445. self._private_method()
  1446. @rx.background
  1447. async def background_task_reset(self):
  1448. """A background task that resets the state."""
  1449. with pytest.raises(ImmutableStateError):
  1450. # Resetting the state should be explicitly blocked.
  1451. self.reset()
  1452. async with self:
  1453. self.order.append("foo")
  1454. self.reset()
  1455. assert not self.order
  1456. async with self:
  1457. self.order.append("reset")
  1458. @rx.background
  1459. async def background_task_generator(self):
  1460. """A background task generator that does nothing.
  1461. Yields:
  1462. None
  1463. """
  1464. yield
  1465. def other(self):
  1466. """Some other event that updates the state."""
  1467. self.order.append("other")
  1468. def _private_method(self):
  1469. """Some private method that updates the state."""
  1470. self.order.append("private")
  1471. async def bad_chain1(self):
  1472. """Test that a background task cannot be chained."""
  1473. await self.background_task()
  1474. async def bad_chain2(self):
  1475. """Test that a background task generator cannot be chained."""
  1476. async for _foo in self.background_task_generator():
  1477. pass
  1478. @pytest.mark.asyncio
  1479. async def test_background_task_no_block(mock_app: rx.App, token: str):
  1480. """Test that a background task does not block other events.
  1481. Args:
  1482. mock_app: An app that will be returned by `get_app()`
  1483. token: A token.
  1484. """
  1485. router_data = {"query": {}}
  1486. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1487. async for update in rx.app.process( # type: ignore
  1488. mock_app,
  1489. Event(
  1490. token=token,
  1491. name=f"{BackgroundTaskState.get_name()}.background_task",
  1492. router_data=router_data,
  1493. payload={},
  1494. ),
  1495. sid="",
  1496. headers={},
  1497. client_ip="",
  1498. ):
  1499. # background task returns empty update immediately
  1500. assert update == StateUpdate()
  1501. # wait for the coroutine to start
  1502. await asyncio.sleep(0.5 if CI else 0.1)
  1503. assert len(mock_app.background_tasks) == 1
  1504. # Process another normal event
  1505. async for update in rx.app.process( # type: ignore
  1506. mock_app,
  1507. Event(
  1508. token=token,
  1509. name=f"{BackgroundTaskState.get_name()}.other",
  1510. router_data=router_data,
  1511. payload={},
  1512. ),
  1513. sid="",
  1514. headers={},
  1515. client_ip="",
  1516. ):
  1517. # other task returns delta
  1518. assert update == StateUpdate(
  1519. delta={
  1520. BackgroundTaskState.get_name(): {
  1521. "order": [
  1522. "background_task:start",
  1523. "other",
  1524. ],
  1525. "computed_order": [
  1526. "background_task:start",
  1527. "other",
  1528. ],
  1529. }
  1530. }
  1531. )
  1532. # Explicit wait for background tasks
  1533. for task in tuple(mock_app.background_tasks):
  1534. await task
  1535. assert not mock_app.background_tasks
  1536. exp_order = [
  1537. "background_task:start",
  1538. "other",
  1539. "background_task:stop",
  1540. "other",
  1541. "private",
  1542. ]
  1543. assert (
  1544. await mock_app.state_manager.get_state(
  1545. _substate_key(token, BackgroundTaskState)
  1546. )
  1547. ).order == exp_order
  1548. assert mock_app.event_namespace is not None
  1549. emit_mock = mock_app.event_namespace.emit
  1550. first_ws_message = json.loads(emit_mock.mock_calls[0].args[1])
  1551. assert first_ws_message["delta"]["background_task_state"].pop("router") is not None
  1552. assert first_ws_message == {
  1553. "delta": {
  1554. "background_task_state": {
  1555. "order": ["background_task:start"],
  1556. "computed_order": ["background_task:start"],
  1557. }
  1558. },
  1559. "events": [],
  1560. "final": True,
  1561. }
  1562. for call in emit_mock.mock_calls[1:5]:
  1563. assert json.loads(call.args[1]) == {
  1564. "delta": {
  1565. "background_task_state": {"computed_order": ["background_task:start"]}
  1566. },
  1567. "events": [],
  1568. "final": True,
  1569. }
  1570. assert json.loads(emit_mock.mock_calls[-2].args[1]) == {
  1571. "delta": {
  1572. "background_task_state": {
  1573. "order": exp_order,
  1574. "computed_order": exp_order,
  1575. "dict_list": {},
  1576. }
  1577. },
  1578. "events": [],
  1579. "final": True,
  1580. }
  1581. assert json.loads(emit_mock.mock_calls[-1].args[1]) == {
  1582. "delta": {
  1583. "background_task_state": {
  1584. "computed_order": exp_order,
  1585. },
  1586. },
  1587. "events": [],
  1588. "final": True,
  1589. }
  1590. @pytest.mark.asyncio
  1591. async def test_background_task_reset(mock_app: rx.App, token: str):
  1592. """Test that a background task calling reset is protected by the state proxy.
  1593. Args:
  1594. mock_app: An app that will be returned by `get_app()`
  1595. token: A token.
  1596. """
  1597. router_data = {"query": {}}
  1598. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1599. async for update in rx.app.process( # type: ignore
  1600. mock_app,
  1601. Event(
  1602. token=token,
  1603. name=f"{BackgroundTaskState.get_name()}.background_task_reset",
  1604. router_data=router_data,
  1605. payload={},
  1606. ),
  1607. sid="",
  1608. headers={},
  1609. client_ip="",
  1610. ):
  1611. # background task returns empty update immediately
  1612. assert update == StateUpdate()
  1613. # Explicit wait for background tasks
  1614. for task in tuple(mock_app.background_tasks):
  1615. await task
  1616. assert not mock_app.background_tasks
  1617. assert (
  1618. await mock_app.state_manager.get_state(
  1619. _substate_key(token, BackgroundTaskState)
  1620. )
  1621. ).order == [
  1622. "reset",
  1623. ]
  1624. @pytest.mark.asyncio
  1625. async def test_background_task_no_chain():
  1626. """Test that a background task cannot be chained."""
  1627. bts = BackgroundTaskState()
  1628. with pytest.raises(RuntimeError):
  1629. await bts.bad_chain1()
  1630. with pytest.raises(RuntimeError):
  1631. await bts.bad_chain2()
  1632. def test_mutable_list(mutable_state):
  1633. """Test that mutable lists are tracked correctly.
  1634. Args:
  1635. mutable_state: A test state.
  1636. """
  1637. assert not mutable_state.dirty_vars
  1638. def assert_array_dirty():
  1639. assert mutable_state.dirty_vars == {"array"}
  1640. mutable_state._clean()
  1641. assert not mutable_state.dirty_vars
  1642. # Test all list operations
  1643. mutable_state.array.append(42)
  1644. assert_array_dirty()
  1645. mutable_state.array.extend([1, 2, 3])
  1646. assert_array_dirty()
  1647. mutable_state.array.insert(0, 0)
  1648. assert_array_dirty()
  1649. mutable_state.array.pop()
  1650. assert_array_dirty()
  1651. mutable_state.array.remove(42)
  1652. assert_array_dirty()
  1653. mutable_state.array.clear()
  1654. assert_array_dirty()
  1655. mutable_state.array += [1, 2, 3]
  1656. assert_array_dirty()
  1657. mutable_state.array.reverse()
  1658. assert_array_dirty()
  1659. mutable_state.array.sort()
  1660. assert_array_dirty()
  1661. mutable_state.array[0] = 666
  1662. assert_array_dirty()
  1663. del mutable_state.array[0]
  1664. assert_array_dirty()
  1665. # Test nested list operations
  1666. mutable_state.array[0] = [1, 2, 3]
  1667. assert_array_dirty()
  1668. mutable_state.array[0].append(4)
  1669. assert_array_dirty()
  1670. assert isinstance(mutable_state.array[0], MutableProxy)
  1671. # Test proxy returned from __iter__
  1672. mutable_state.array = [{}]
  1673. assert_array_dirty()
  1674. assert isinstance(mutable_state.array[0], MutableProxy)
  1675. for item in mutable_state.array:
  1676. assert isinstance(item, MutableProxy)
  1677. item["foo"] = "bar"
  1678. assert_array_dirty()
  1679. def test_mutable_dict(mutable_state):
  1680. """Test that mutable dicts are tracked correctly.
  1681. Args:
  1682. mutable_state: A test state.
  1683. """
  1684. assert not mutable_state.dirty_vars
  1685. def assert_hashmap_dirty():
  1686. assert mutable_state.dirty_vars == {"hashmap"}
  1687. mutable_state._clean()
  1688. assert not mutable_state.dirty_vars
  1689. # Test all dict operations
  1690. mutable_state.hashmap.update({"new_key": 43})
  1691. assert_hashmap_dirty()
  1692. assert mutable_state.hashmap.setdefault("another_key", 66) == "another_value"
  1693. assert_hashmap_dirty()
  1694. assert mutable_state.hashmap.setdefault("setdefault_key", 67) == 67
  1695. assert_hashmap_dirty()
  1696. assert mutable_state.hashmap.setdefault("setdefault_key", 68) == 67
  1697. assert_hashmap_dirty()
  1698. assert mutable_state.hashmap.pop("new_key") == 43
  1699. assert_hashmap_dirty()
  1700. mutable_state.hashmap.popitem()
  1701. assert_hashmap_dirty()
  1702. mutable_state.hashmap.clear()
  1703. assert_hashmap_dirty()
  1704. mutable_state.hashmap["new_key"] = 42
  1705. assert_hashmap_dirty()
  1706. del mutable_state.hashmap["new_key"]
  1707. assert_hashmap_dirty()
  1708. if sys.version_info >= (3, 9):
  1709. mutable_state.hashmap |= {"new_key": 44}
  1710. assert_hashmap_dirty()
  1711. # Test nested dict operations
  1712. mutable_state.hashmap["array"] = []
  1713. assert_hashmap_dirty()
  1714. mutable_state.hashmap["array"].append(1)
  1715. assert_hashmap_dirty()
  1716. mutable_state.hashmap["dict"] = {}
  1717. assert_hashmap_dirty()
  1718. mutable_state.hashmap["dict"]["key"] = 42
  1719. assert_hashmap_dirty()
  1720. mutable_state.hashmap["dict"]["dict"] = {}
  1721. assert_hashmap_dirty()
  1722. mutable_state.hashmap["dict"]["dict"]["key"] = 43
  1723. assert_hashmap_dirty()
  1724. # Test proxy returned from `setdefault` and `get`
  1725. mutable_value = mutable_state.hashmap.setdefault("setdefault_mutable_key", [])
  1726. assert_hashmap_dirty()
  1727. assert mutable_value == []
  1728. assert isinstance(mutable_value, MutableProxy)
  1729. mutable_value.append("foo")
  1730. assert_hashmap_dirty()
  1731. mutable_value_other_ref = mutable_state.hashmap.get("setdefault_mutable_key")
  1732. assert isinstance(mutable_value_other_ref, MutableProxy)
  1733. assert mutable_value is not mutable_value_other_ref
  1734. assert mutable_value == mutable_value_other_ref
  1735. assert not mutable_state.dirty_vars
  1736. mutable_value_other_ref.append("bar")
  1737. assert_hashmap_dirty()
  1738. # `pop` should NOT return a proxy, because the returned value is no longer in the dict
  1739. mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key")
  1740. assert not isinstance(mutable_value_third_ref, MutableProxy)
  1741. assert_hashmap_dirty()
  1742. mutable_value_third_ref.append("baz")
  1743. assert not mutable_state.dirty_vars
  1744. # Unfortunately previous refs still will mark the state dirty... nothing doing about that
  1745. assert mutable_value.pop()
  1746. assert_hashmap_dirty()
  1747. def test_mutable_set(mutable_state):
  1748. """Test that mutable sets are tracked correctly.
  1749. Args:
  1750. mutable_state: A test state.
  1751. """
  1752. assert not mutable_state.dirty_vars
  1753. def assert_set_dirty():
  1754. assert mutable_state.dirty_vars == {"test_set"}
  1755. mutable_state._clean()
  1756. assert not mutable_state.dirty_vars
  1757. # Test all set operations
  1758. mutable_state.test_set.add(42)
  1759. assert_set_dirty()
  1760. mutable_state.test_set.update([1, 2, 3])
  1761. assert_set_dirty()
  1762. mutable_state.test_set.remove(42)
  1763. assert_set_dirty()
  1764. mutable_state.test_set.discard(3)
  1765. assert_set_dirty()
  1766. mutable_state.test_set.pop()
  1767. assert_set_dirty()
  1768. mutable_state.test_set.intersection_update([1, 2, 3])
  1769. assert_set_dirty()
  1770. mutable_state.test_set.difference_update([99])
  1771. assert_set_dirty()
  1772. mutable_state.test_set.symmetric_difference_update([102, 99])
  1773. assert_set_dirty()
  1774. mutable_state.test_set |= {1, 2, 3}
  1775. assert_set_dirty()
  1776. mutable_state.test_set &= {2, 3, 4}
  1777. assert_set_dirty()
  1778. mutable_state.test_set -= {2}
  1779. assert_set_dirty()
  1780. mutable_state.test_set ^= {42}
  1781. assert_set_dirty()
  1782. mutable_state.test_set.clear()
  1783. assert_set_dirty()
  1784. def test_mutable_custom(mutable_state):
  1785. """Test that mutable custom types derived from Base are tracked correctly.
  1786. Args:
  1787. mutable_state: A test state.
  1788. """
  1789. assert not mutable_state.dirty_vars
  1790. def assert_custom_dirty():
  1791. assert mutable_state.dirty_vars == {"custom"}
  1792. mutable_state._clean()
  1793. assert not mutable_state.dirty_vars
  1794. mutable_state.custom.foo = "bar"
  1795. assert_custom_dirty()
  1796. mutable_state.custom.array.append(42)
  1797. assert_custom_dirty()
  1798. mutable_state.custom.hashmap["key"] = 68
  1799. assert_custom_dirty()
  1800. mutable_state.custom.test_set.add(42)
  1801. assert_custom_dirty()
  1802. mutable_state.custom.custom.bar = "baz"
  1803. assert_custom_dirty()
  1804. def test_mutable_backend(mutable_state):
  1805. """Test that mutable backend vars are tracked correctly.
  1806. Args:
  1807. mutable_state: A test state.
  1808. """
  1809. assert not mutable_state.dirty_vars
  1810. def assert_custom_dirty():
  1811. assert mutable_state.dirty_vars == {"_be_custom"}
  1812. mutable_state._clean()
  1813. assert not mutable_state.dirty_vars
  1814. mutable_state._be_custom.foo = "bar"
  1815. assert_custom_dirty()
  1816. mutable_state._be_custom.array.append(42)
  1817. assert_custom_dirty()
  1818. mutable_state._be_custom.hashmap["key"] = 68
  1819. assert_custom_dirty()
  1820. mutable_state._be_custom.test_set.add(42)
  1821. assert_custom_dirty()
  1822. mutable_state._be_custom.custom.bar = "baz"
  1823. assert_custom_dirty()
  1824. @pytest.mark.parametrize(
  1825. ("copy_func",),
  1826. [
  1827. (copy.copy,),
  1828. (copy.deepcopy,),
  1829. ],
  1830. )
  1831. def test_mutable_copy(mutable_state, copy_func):
  1832. """Test that mutable types are copied correctly.
  1833. Args:
  1834. mutable_state: A test state.
  1835. copy_func: A copy function.
  1836. """
  1837. ms_copy = copy_func(mutable_state)
  1838. assert ms_copy is not mutable_state
  1839. for attr in ("array", "hashmap", "test_set", "custom"):
  1840. assert getattr(ms_copy, attr) == getattr(mutable_state, attr)
  1841. assert getattr(ms_copy, attr) is not getattr(mutable_state, attr)
  1842. ms_copy.custom.array.append(42)
  1843. assert "custom" in ms_copy.dirty_vars
  1844. if copy_func is copy.copy:
  1845. assert "custom" in mutable_state.dirty_vars
  1846. else:
  1847. assert not mutable_state.dirty_vars
  1848. @pytest.mark.parametrize(
  1849. ("copy_func",),
  1850. [
  1851. (copy.copy,),
  1852. (copy.deepcopy,),
  1853. ],
  1854. )
  1855. def test_mutable_copy_vars(mutable_state, copy_func):
  1856. """Test that mutable types are copied correctly.
  1857. Args:
  1858. mutable_state: A test state.
  1859. copy_func: A copy function.
  1860. """
  1861. for attr in ("array", "hashmap", "test_set", "custom"):
  1862. var_orig = getattr(mutable_state, attr)
  1863. var_copy = copy_func(var_orig)
  1864. assert var_orig is not var_copy
  1865. assert var_orig == var_copy
  1866. # copied vars should never be proxies, as they by definition are no longer attached to the state.
  1867. assert not isinstance(var_copy, MutableProxy)
  1868. def test_duplicate_substate_class(mocker):
  1869. mocker.patch("reflex.state.is_testing_env", lambda: False)
  1870. with pytest.raises(ValueError):
  1871. class TestState(BaseState):
  1872. pass
  1873. class ChildTestState(TestState): # type: ignore # noqa
  1874. pass
  1875. class ChildTestState(TestState): # type: ignore # noqa
  1876. pass
  1877. return TestState
  1878. class Foo(Base):
  1879. """A class containing a list of str."""
  1880. tags: List[str] = ["123", "456"]
  1881. def test_json_dumps_with_mutables():
  1882. """Test that json.dumps works with Base vars inside mutable types."""
  1883. class MutableContainsBase(BaseState):
  1884. items: List[Foo] = [Foo()]
  1885. dict_val = MutableContainsBase().dict()
  1886. assert isinstance(dict_val[MutableContainsBase.get_full_name()]["items"][0], dict)
  1887. val = json_dumps(dict_val)
  1888. f_items = '[{"tags": ["123", "456"]}]'
  1889. f_formatted_router = str(formatted_router).replace("'", '"')
  1890. assert (
  1891. val
  1892. == f'{{"{MutableContainsBase.get_full_name()}": {{"items": {f_items}, "router": {f_formatted_router}}}}}'
  1893. )
  1894. def test_reset_with_mutables():
  1895. """Calling reset should always reset fields to a copy of the defaults."""
  1896. default = [[0, 0], [0, 1], [1, 1]]
  1897. copied_default = copy.deepcopy(default)
  1898. class MutableResetState(BaseState):
  1899. items: List[List[int]] = default
  1900. instance = MutableResetState()
  1901. assert instance.items.__wrapped__ is not default # type: ignore
  1902. assert instance.items == default == copied_default
  1903. instance.items.append([3, 3])
  1904. assert instance.items != default
  1905. assert instance.items != copied_default
  1906. instance.reset()
  1907. assert instance.items.__wrapped__ is not default # type: ignore
  1908. assert instance.items == default == copied_default
  1909. instance.items.append([3, 3])
  1910. assert instance.items != default
  1911. assert instance.items != copied_default
  1912. instance.reset()
  1913. assert instance.items.__wrapped__ is not default # type: ignore
  1914. assert instance.items == default == copied_default
  1915. instance.items.append([3, 3])
  1916. assert instance.items != default
  1917. assert instance.items != copied_default
  1918. class Custom1(Base):
  1919. """A custom class with a str field."""
  1920. foo: str
  1921. def set_foo(self, val: str):
  1922. """Set the attribute foo.
  1923. Args:
  1924. val: The value to set.
  1925. """
  1926. self.foo = val
  1927. def double_foo(self) -> str:
  1928. """Concantenate foo with foo.
  1929. Returns:
  1930. foo + foo
  1931. """
  1932. return self.foo + self.foo
  1933. class Custom2(Base):
  1934. """A custom class with a Custom1 field."""
  1935. c1: Optional[Custom1] = None
  1936. c1r: Custom1
  1937. def set_c1r_foo(self, val: str):
  1938. """Set the foo attribute of the c1 field.
  1939. Args:
  1940. val: The value to set.
  1941. """
  1942. self.c1r.set_foo(val)
  1943. class Custom3(Base):
  1944. """A custom class with a Custom2 field."""
  1945. c2: Optional[Custom2] = None
  1946. c2r: Custom2
  1947. def test_state_union_optional():
  1948. """Test that state can be defined with Union and Optional vars."""
  1949. class UnionState(BaseState):
  1950. int_float: Union[int, float] = 0
  1951. opt_int: Optional[int]
  1952. c3: Optional[Custom3]
  1953. c3i: Custom3 # implicitly required
  1954. c3r: Custom3 = Custom3(c2r=Custom2(c1r=Custom1(foo="")))
  1955. custom_union: Union[Custom1, Custom2, Custom3] = Custom1(foo="")
  1956. assert UnionState.c3.c2._var_name == "c3?.c2" # type: ignore
  1957. assert UnionState.c3.c2.c1._var_name == "c3?.c2?.c1" # type: ignore
  1958. assert UnionState.c3.c2.c1.foo._var_name == "c3?.c2?.c1?.foo" # type: ignore
  1959. assert UnionState.c3.c2.c1r.foo._var_name == "c3?.c2?.c1r.foo" # type: ignore
  1960. assert UnionState.c3.c2r.c1._var_name == "c3?.c2r.c1" # type: ignore
  1961. assert UnionState.c3.c2r.c1.foo._var_name == "c3?.c2r.c1?.foo" # type: ignore
  1962. assert UnionState.c3.c2r.c1r.foo._var_name == "c3?.c2r.c1r.foo" # type: ignore
  1963. assert UnionState.c3i.c2._var_name == "c3i.c2" # type: ignore
  1964. assert UnionState.c3r.c2._var_name == "c3r.c2" # type: ignore
  1965. assert UnionState.custom_union.foo is not None # type: ignore
  1966. assert UnionState.custom_union.c1 is not None # type: ignore
  1967. assert UnionState.custom_union.c1r is not None # type: ignore
  1968. assert UnionState.custom_union.c2 is not None # type: ignore
  1969. assert UnionState.custom_union.c2r is not None # type: ignore
  1970. assert types.is_optional(UnionState.opt_int._var_type) # type: ignore
  1971. assert types.is_union(UnionState.int_float._var_type) # type: ignore
  1972. def test_set_base_field_via_setter():
  1973. """When calling a setter on a Base instance, also track changes."""
  1974. class BaseFieldSetterState(BaseState):
  1975. c1: Custom1 = Custom1(foo="")
  1976. c2: Custom2 = Custom2(c1r=Custom1(foo=""))
  1977. bfss = BaseFieldSetterState()
  1978. assert "c1" not in bfss.dirty_vars
  1979. # Non-mutating function, not dirty
  1980. bfss.c1.double_foo()
  1981. assert "c1" not in bfss.dirty_vars
  1982. # Mutating function, dirty
  1983. bfss.c1.set_foo("bar")
  1984. assert "c1" in bfss.dirty_vars
  1985. bfss.dirty_vars.clear()
  1986. assert "c1" not in bfss.dirty_vars
  1987. # Mutating function from Base, dirty
  1988. bfss.c1.set(foo="bar")
  1989. assert "c1" in bfss.dirty_vars
  1990. bfss.dirty_vars.clear()
  1991. assert "c1" not in bfss.dirty_vars
  1992. # Assert identity of MutableProxy
  1993. mp = bfss.c1
  1994. assert isinstance(mp, MutableProxy)
  1995. mp2 = mp.set()
  1996. assert mp is mp2
  1997. mp3 = bfss.c1.set()
  1998. assert mp is not mp3
  1999. # Since none of these set calls had values, the state should not be dirty
  2000. assert not bfss.dirty_vars
  2001. # Chained Mutating function, dirty
  2002. bfss.c2.set_c1r_foo("baz")
  2003. assert "c2" in bfss.dirty_vars
  2004. def exp_is_hydrated(state: State, is_hydrated: bool = True) -> Dict[str, Any]:
  2005. """Expected IS_HYDRATED delta that would be emitted by HydrateMiddleware.
  2006. Args:
  2007. state: the State that is hydrated.
  2008. is_hydrated: whether the state is hydrated.
  2009. Returns:
  2010. dict similar to that returned by `State.get_delta` with IS_HYDRATED: is_hydrated
  2011. """
  2012. return {state.get_full_name(): {CompileVars.IS_HYDRATED: is_hydrated}}
  2013. class OnLoadState(State):
  2014. """A test state with no return in handler."""
  2015. num: int = 0
  2016. def test_handler(self):
  2017. """Test handler."""
  2018. self.num += 1
  2019. class OnLoadState2(State):
  2020. """A test state with return in handler."""
  2021. num: int = 0
  2022. name: str
  2023. def test_handler(self):
  2024. """Test handler that calls another handler.
  2025. Returns:
  2026. Chain of EventHandlers
  2027. """
  2028. self.num += 1
  2029. return self.change_name
  2030. def change_name(self):
  2031. """Test handler to change name."""
  2032. self.name = "random"
  2033. class OnLoadState3(State):
  2034. """A test state with async handler."""
  2035. num: int = 0
  2036. async def test_handler(self):
  2037. """Test handler."""
  2038. self.num += 1
  2039. @pytest.mark.asyncio
  2040. @pytest.mark.parametrize(
  2041. "test_state, expected",
  2042. [
  2043. (OnLoadState, {"on_load_state": {"num": 1}}),
  2044. (OnLoadState2, {"on_load_state2": {"num": 1}}),
  2045. (OnLoadState3, {"on_load_state3": {"num": 1}}),
  2046. ],
  2047. )
  2048. async def test_preprocess(app_module_mock, token, test_state, expected, mocker):
  2049. """Test that a state hydrate event is processed correctly.
  2050. Args:
  2051. app_module_mock: The app module that will be returned by get_app().
  2052. token: A token.
  2053. test_state: State to process event.
  2054. expected: Expected delta.
  2055. mocker: pytest mock object.
  2056. """
  2057. mocker.patch(
  2058. "reflex.state.State.class_subclasses", {test_state, OnLoadInternalState}
  2059. )
  2060. app = app_module_mock.app = App(
  2061. state=State, load_events={"index": [test_state.test_handler]}
  2062. )
  2063. state = State()
  2064. updates = []
  2065. async for update in rx.app.process(
  2066. app=app,
  2067. event=Event(
  2068. token=token,
  2069. name=f"{state.get_name()}.{CompileVars.ON_LOAD_INTERNAL}",
  2070. router_data={RouteVar.PATH: "/", RouteVar.ORIGIN: "/", RouteVar.QUERY: {}},
  2071. ),
  2072. sid="sid",
  2073. headers={},
  2074. client_ip="",
  2075. ):
  2076. assert isinstance(update, StateUpdate)
  2077. updates.append(update)
  2078. assert len(updates) == 1
  2079. assert updates[0].delta["state"].pop("router") is not None
  2080. assert updates[0].delta == exp_is_hydrated(state, False)
  2081. events = updates[0].events
  2082. assert len(events) == 2
  2083. assert (await state._process(events[0]).__anext__()).delta == {
  2084. test_state.get_full_name(): {"num": 1}
  2085. }
  2086. assert (await state._process(events[1]).__anext__()).delta == exp_is_hydrated(state)
  2087. @pytest.mark.asyncio
  2088. async def test_preprocess_multiple_load_events(app_module_mock, token, mocker):
  2089. """Test that a state hydrate event for multiple on-load events is processed correctly.
  2090. Args:
  2091. app_module_mock: The app module that will be returned by get_app().
  2092. token: A token.
  2093. mocker: pytest mock object.
  2094. """
  2095. mocker.patch(
  2096. "reflex.state.State.class_subclasses", {OnLoadState, OnLoadInternalState}
  2097. )
  2098. app = app_module_mock.app = App(
  2099. state=State,
  2100. load_events={"index": [OnLoadState.test_handler, OnLoadState.test_handler]},
  2101. )
  2102. state = State()
  2103. updates = []
  2104. async for update in rx.app.process(
  2105. app=app,
  2106. event=Event(
  2107. token=token,
  2108. name=f"{state.get_full_name()}.{CompileVars.ON_LOAD_INTERNAL}",
  2109. router_data={RouteVar.PATH: "/", RouteVar.ORIGIN: "/", RouteVar.QUERY: {}},
  2110. ),
  2111. sid="sid",
  2112. headers={},
  2113. client_ip="",
  2114. ):
  2115. assert isinstance(update, StateUpdate)
  2116. updates.append(update)
  2117. assert len(updates) == 1
  2118. assert updates[0].delta["state"].pop("router") is not None
  2119. assert updates[0].delta == exp_is_hydrated(state, False)
  2120. events = updates[0].events
  2121. assert len(events) == 3
  2122. assert (await state._process(events[0]).__anext__()).delta == {
  2123. OnLoadState.get_full_name(): {"num": 1}
  2124. }
  2125. assert (await state._process(events[1]).__anext__()).delta == {
  2126. OnLoadState.get_full_name(): {"num": 2}
  2127. }
  2128. assert (await state._process(events[2]).__anext__()).delta == exp_is_hydrated(state)
  2129. @pytest.mark.asyncio
  2130. async def test_get_state(mock_app: rx.App, token: str):
  2131. """Test that a get_state populates the top level state and delta calculation is correct.
  2132. Args:
  2133. mock_app: An app that will be returned by `get_app()`
  2134. token: A token.
  2135. """
  2136. mock_app.state_manager.state = mock_app.state = TestState
  2137. # Get instance of ChildState2.
  2138. test_state = await mock_app.state_manager.get_state(
  2139. _substate_key(token, ChildState2)
  2140. )
  2141. assert isinstance(test_state, TestState)
  2142. if isinstance(mock_app.state_manager, StateManagerMemory):
  2143. # All substates are available
  2144. assert tuple(sorted(test_state.substates)) == (
  2145. "child_state",
  2146. "child_state2",
  2147. "child_state3",
  2148. )
  2149. else:
  2150. # Sibling states are only populated if they have computed vars
  2151. assert tuple(sorted(test_state.substates)) == ("child_state2", "child_state3")
  2152. # Because ChildState3 has a computed var, it is always dirty, and always populated.
  2153. assert (
  2154. test_state.substates["child_state3"].substates["grandchild_state3"].computed
  2155. == ""
  2156. )
  2157. # Get the child_state2 directly.
  2158. child_state2_direct = test_state.get_substate(["child_state2"])
  2159. child_state2_get_state = await test_state.get_state(ChildState2)
  2160. # These should be the same object.
  2161. assert child_state2_direct is child_state2_get_state
  2162. # Get arbitrary GrandchildState.
  2163. grandchild_state = await child_state2_get_state.get_state(GrandchildState)
  2164. assert isinstance(grandchild_state, GrandchildState)
  2165. # Now the original root should have all substates populated.
  2166. assert tuple(sorted(test_state.substates)) == (
  2167. "child_state",
  2168. "child_state2",
  2169. "child_state3",
  2170. )
  2171. # ChildState should be retrievable
  2172. child_state_direct = test_state.get_substate(["child_state"])
  2173. child_state_get_state = await test_state.get_state(ChildState)
  2174. # These should be the same object.
  2175. assert child_state_direct is child_state_get_state
  2176. # GrandchildState instance should be the same as the one retrieved from the child_state2.
  2177. assert grandchild_state is child_state_direct.get_substate(["grandchild_state"])
  2178. grandchild_state.value2 = "set_value"
  2179. assert test_state.get_delta() == {
  2180. TestState.get_full_name(): {
  2181. "sum": 3.14,
  2182. "upper": "",
  2183. },
  2184. GrandchildState.get_full_name(): {
  2185. "value2": "set_value",
  2186. },
  2187. GrandchildState3.get_full_name(): {
  2188. "computed": "",
  2189. },
  2190. }
  2191. # Get a fresh instance
  2192. new_test_state = await mock_app.state_manager.get_state(
  2193. _substate_key(token, ChildState2)
  2194. )
  2195. assert isinstance(new_test_state, TestState)
  2196. if isinstance(mock_app.state_manager, StateManagerMemory):
  2197. # In memory, it's the same instance
  2198. assert new_test_state is test_state
  2199. test_state._clean()
  2200. # All substates are available
  2201. assert tuple(sorted(new_test_state.substates)) == (
  2202. "child_state",
  2203. "child_state2",
  2204. "child_state3",
  2205. )
  2206. else:
  2207. # With redis, we get a whole new instance
  2208. assert new_test_state is not test_state
  2209. # Sibling states are only populated if they have computed vars
  2210. assert tuple(sorted(new_test_state.substates)) == (
  2211. "child_state2",
  2212. "child_state3",
  2213. )
  2214. # Set a value on child_state2, should update cached var in grandchild_state2
  2215. child_state2 = new_test_state.get_substate(("child_state2",))
  2216. child_state2.value = "set_c2_value"
  2217. assert new_test_state.get_delta() == {
  2218. TestState.get_full_name(): {
  2219. "sum": 3.14,
  2220. "upper": "",
  2221. },
  2222. ChildState2.get_full_name(): {
  2223. "value": "set_c2_value",
  2224. },
  2225. GrandchildState2.get_full_name(): {
  2226. "cached": "set_c2_value",
  2227. },
  2228. GrandchildState3.get_full_name(): {
  2229. "computed": "",
  2230. },
  2231. }
  2232. @pytest.mark.asyncio
  2233. async def test_get_state_from_sibling_not_cached(mock_app: rx.App, token: str):
  2234. """A test simulating update_vars_internal when setting cookies with computed vars.
  2235. In that case, a sibling state, UpdateVarsInternalState handles the fetching
  2236. of states that need to have values set. Only the states that have a computed
  2237. var are pre-fetched (like Child3 in this test), so `get_state` needs to
  2238. avoid refetching those already-cached states when getting substates,
  2239. otherwise the set values will be overridden by the freshly deserialized
  2240. version and lost.
  2241. Explicit regression test for https://github.com/reflex-dev/reflex/issues/2851.
  2242. Args:
  2243. mock_app: An app that will be returned by `get_app()`
  2244. token: A token.
  2245. """
  2246. class Parent(BaseState):
  2247. """A root state like rx.State."""
  2248. parent_var: int = 0
  2249. class Child(Parent):
  2250. """A state simulating UpdateVarsInternalState."""
  2251. pass
  2252. class Child2(Parent):
  2253. """An unconnected child state."""
  2254. pass
  2255. class Child3(Parent):
  2256. """A child state with a computed var causing it to be pre-fetched.
  2257. If child3_var gets set to a value, and `get_state` erroneously
  2258. re-fetches it from redis, the value will be lost.
  2259. """
  2260. child3_var: int = 0
  2261. @rx.var
  2262. def v(self):
  2263. pass
  2264. class Grandchild3(Child3):
  2265. """An extra layer of substate to catch an issue discovered in
  2266. _determine_missing_parent_states while writing the regression test where
  2267. invalid parent state names were being constructed.
  2268. """
  2269. pass
  2270. class GreatGrandchild3(Grandchild3):
  2271. """Fetching this state wants to also fetch Child3 as a missing parent.
  2272. However, Child3 should already be cached in the state tree because it
  2273. has a computed var.
  2274. """
  2275. pass
  2276. mock_app.state_manager.state = mock_app.state = Parent
  2277. # Get the top level state via unconnected sibling.
  2278. root = await mock_app.state_manager.get_state(_substate_key(token, Child))
  2279. # Set value in parent_var to assert it does not get refetched later.
  2280. root.parent_var = 1
  2281. if isinstance(mock_app.state_manager, StateManagerRedis):
  2282. # When redis is used, only states with computed vars are pre-fetched.
  2283. assert "child2" not in root.substates
  2284. assert "child3" in root.substates # (due to @rx.var)
  2285. # Get the unconnected sibling state, which will be used to `get_state` other instances.
  2286. child = root.get_substate(Child.get_full_name().split("."))
  2287. # Get an uncached child state.
  2288. child2 = await child.get_state(Child2)
  2289. assert child2.parent_var == 1
  2290. # Set value on already-cached Child3 state (prefetched because it has a Computed Var).
  2291. child3 = await child.get_state(Child3)
  2292. child3.child3_var = 1
  2293. # Get uncached great_grandchild3 state.
  2294. great_grandchild3 = await child.get_state(GreatGrandchild3)
  2295. # Assert that we didn't re-fetch the parent and child3 state from redis
  2296. assert great_grandchild3.parent_var == 1
  2297. assert great_grandchild3.child3_var == 1
  2298. # Save a reference to the rx.State to shadow the name State for testing.
  2299. RxState = State
  2300. def test_potentially_dirty_substates():
  2301. """Test that potentially_dirty_substates returns the correct substates.
  2302. Even if the name "State" is shadowed, it should still work correctly.
  2303. """
  2304. class State(RxState):
  2305. @ComputedVar
  2306. def foo(self) -> str:
  2307. return ""
  2308. class C1(State):
  2309. @ComputedVar
  2310. def bar(self) -> str:
  2311. return ""
  2312. assert RxState._potentially_dirty_substates() == {State}
  2313. assert State._potentially_dirty_substates() == {C1}
  2314. assert C1._potentially_dirty_substates() == set()
  2315. @pytest.mark.asyncio
  2316. async def test_setvar(mock_app: rx.App, token: str):
  2317. """Test that setvar works correctly.
  2318. Args:
  2319. mock_app: An app that will be returned by `get_app()`
  2320. token: A token.
  2321. """
  2322. state = await mock_app.state_manager.get_state(_substate_key(token, TestState))
  2323. # Set Var in same state (with Var type casting)
  2324. for event in rx.event.fix_events(
  2325. [TestState.setvar("num1", 42), TestState.setvar("num2", "4.2")], token
  2326. ):
  2327. async for update in state._process(event):
  2328. print(update)
  2329. assert state.num1 == 42
  2330. assert state.num2 == 4.2
  2331. # Set Var in parent state
  2332. for event in rx.event.fix_events([GrandchildState.setvar("array", [43])], token):
  2333. async for update in state._process(event):
  2334. print(update)
  2335. assert state.array == [43]
  2336. # Cannot setvar for non-existant var
  2337. with pytest.raises(AttributeError):
  2338. TestState.setvar("non_existant_var")
  2339. # Cannot setvar for computed vars
  2340. with pytest.raises(AttributeError):
  2341. TestState.setvar("sum")
  2342. # Cannot setvar with non-string
  2343. with pytest.raises(ValueError):
  2344. TestState.setvar(42, 42)
  2345. @pytest.mark.skipif("REDIS_URL" not in os.environ, reason="Test requires redis")
  2346. @pytest.mark.parametrize(
  2347. "expiration_kwargs, expected_values",
  2348. [
  2349. ({"redis_lock_expiration": 20000}, (20000, constants.Expiration.TOKEN)),
  2350. (
  2351. {"redis_lock_expiration": 50000, "redis_token_expiration": 5600},
  2352. (50000, 5600),
  2353. ),
  2354. ({"redis_token_expiration": 7600}, (constants.Expiration.LOCK, 7600)),
  2355. ],
  2356. )
  2357. def test_redis_state_manager_config_knobs(tmp_path, expiration_kwargs, expected_values):
  2358. proj_root = tmp_path / "project1"
  2359. proj_root.mkdir()
  2360. config_items = ",\n ".join(
  2361. f"{key} = {value}" for key, value in expiration_kwargs.items()
  2362. )
  2363. config_string = f"""
  2364. import reflex as rx
  2365. config = rx.Config(
  2366. app_name="project1",
  2367. redis_url="redis://localhost:6379",
  2368. {config_items}
  2369. )
  2370. """
  2371. (proj_root / "rxconfig.py").write_text(dedent(config_string))
  2372. with chdir(proj_root):
  2373. # reload config for each parameter to avoid stale values
  2374. reflex.config.get_config(reload=True)
  2375. from reflex.state import State, StateManager
  2376. state_manager = StateManager.create(state=State)
  2377. assert state_manager.lock_expiration == expected_values[0] # type: ignore
  2378. assert state_manager.token_expiration == expected_values[1] # type: ignore