test_state.py 88 KB

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