test_state.py 103 KB

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