test_state.py 102 KB

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