test_state.py 107 KB

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