test_state.py 86 KB

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