test_state.py 92 KB

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