test_state.py 122 KB

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