test_state.py 107 KB

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