test_state.py 118 KB

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