test_state.py 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702
  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 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 set(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 = {
  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 set(cls.event_handlers.keys()).intersection(expected) == expected
  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_token(test_state, mocker, router_data):
  629. """Test that the token obtained from the router_data is correct.
  630. Args:
  631. test_state: The test state.
  632. mocker: Pytest Mocker object.
  633. router_data: The router data fixture.
  634. """
  635. mocker.patch.object(test_state, "router_data", router_data)
  636. assert test_state.get_token() == "b181904c-3953-4a79-dc18-ae9518c22f05"
  637. def test_get_sid(test_state, mocker, router_data):
  638. """Test getting session id.
  639. Args:
  640. test_state: A state.
  641. mocker: Pytest Mocker object.
  642. router_data: The router data fixture.
  643. """
  644. mocker.patch.object(test_state, "router_data", router_data)
  645. assert test_state.get_sid() == "9fpxSzPb9aFMb4wFAAAH"
  646. def test_get_headers(test_state, mocker, router_data, router_data_headers):
  647. """Test getting client headers.
  648. Args:
  649. test_state: A state.
  650. mocker: Pytest Mocker object.
  651. router_data: The router data fixture.
  652. router_data_headers: The expected headers.
  653. """
  654. mocker.patch.object(test_state, "router_data", router_data)
  655. assert test_state.get_headers() == router_data_headers
  656. def test_get_client_ip(test_state, mocker, router_data):
  657. """Test getting client IP.
  658. Args:
  659. test_state: A state.
  660. mocker: Pytest Mocker object.
  661. router_data: The router data fixture.
  662. """
  663. mocker.patch.object(test_state, "router_data", router_data)
  664. assert test_state.get_client_ip() == "127.0.0.1"
  665. def test_get_cookies(test_state, mocker, router_data):
  666. """Test getting client cookies.
  667. Args:
  668. test_state: A state.
  669. mocker: Pytest Mocker object.
  670. router_data: The router data fixture.
  671. """
  672. mocker.patch.object(test_state, "router_data", router_data)
  673. assert test_state.get_cookies() == {
  674. "csrftoken": "mocktoken",
  675. "name": "reflex",
  676. "list_cookies": ["some", "random", "cookies"],
  677. "dict_cookies": {"name": "reflex"},
  678. "val": True,
  679. }
  680. def test_get_current_page(test_state):
  681. assert test_state.get_current_page() == ""
  682. route = "mypage/subpage"
  683. test_state.router = RouterData({RouteVar.PATH: route})
  684. assert test_state.get_current_page() == route
  685. def test_get_query_params(test_state):
  686. assert test_state.get_query_params() == {}
  687. params = {"p1": "a", "p2": "b"}
  688. test_state.router_data = {RouteVar.QUERY: params}
  689. assert test_state.get_query_params() == params
  690. def test_add_var():
  691. class DynamicState(BaseState):
  692. pass
  693. ds1 = DynamicState()
  694. assert "dynamic_int" not in ds1.__dict__
  695. assert not hasattr(ds1, "dynamic_int")
  696. ds1.add_var("dynamic_int", int, 42)
  697. # Existing instances get the BaseVar
  698. assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # type: ignore
  699. # New instances get an actual value with the default
  700. assert DynamicState().dynamic_int == 42
  701. ds1.add_var("dynamic_list", List[int], [5, 10])
  702. assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # type: ignore
  703. ds2 = DynamicState()
  704. assert ds2.dynamic_list == [5, 10]
  705. ds2.dynamic_list.append(15)
  706. assert ds2.dynamic_list == [5, 10, 15]
  707. assert DynamicState().dynamic_list == [5, 10]
  708. ds1.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  709. assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  710. assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  711. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  712. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  713. def test_add_var_default_handlers(test_state):
  714. test_state.add_var("rand_int", int, 10)
  715. assert "set_rand_int" in test_state.event_handlers
  716. assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
  717. class InterdependentState(BaseState):
  718. """A state with 3 vars and 3 computed vars.
  719. x: a variable that no computed var depends on
  720. v1: a varable that one computed var directly depeneds on
  721. _v2: a backend variable that one computed var directly depends on
  722. v1x2: a computed var that depends on v1
  723. v2x2: a computed var that depends on backend var _v2
  724. v1x2x2: a computed var that depends on computed var v1x2
  725. """
  726. x: int = 0
  727. v1: int = 0
  728. _v2: int = 1
  729. @rx.cached_var
  730. def v1x2(self) -> int:
  731. """Depends on var v1.
  732. Returns:
  733. Var v1 multiplied by 2
  734. """
  735. return self.v1 * 2
  736. @rx.cached_var
  737. def v2x2(self) -> int:
  738. """Depends on backend var _v2.
  739. Returns:
  740. backend var _v2 multiplied by 2
  741. """
  742. return self._v2 * 2
  743. @rx.cached_var
  744. def v1x2x2(self) -> int:
  745. """Depends on ComputedVar v1x2.
  746. Returns:
  747. ComputedVar v1x2 multiplied by 2
  748. """
  749. return self.v1x2 * 2 # type: ignore
  750. @pytest.fixture
  751. def interdependent_state() -> BaseState:
  752. """A state with varying dependency between vars.
  753. Returns:
  754. instance of InterdependentState
  755. """
  756. s = InterdependentState()
  757. s.dict() # prime initial relationships by accessing all ComputedVars
  758. return s
  759. def test_not_dirty_computed_var_from_var(interdependent_state):
  760. """Set Var that no ComputedVar depends on, expect no recalculation.
  761. Args:
  762. interdependent_state: A state with varying Var dependencies.
  763. """
  764. interdependent_state.x = 5
  765. assert interdependent_state.get_delta() == {
  766. interdependent_state.get_full_name(): {"x": 5},
  767. }
  768. def test_dirty_computed_var_from_var(interdependent_state):
  769. """Set Var that ComputedVar depends on, expect recalculation.
  770. The other ComputedVar depends on the changed ComputedVar and should also be
  771. recalculated. No other ComputedVars should be recalculated.
  772. Args:
  773. interdependent_state: A state with varying Var dependencies.
  774. """
  775. interdependent_state.v1 = 1
  776. assert interdependent_state.get_delta() == {
  777. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  778. }
  779. def test_dirty_computed_var_from_backend_var(interdependent_state):
  780. """Set backend var that ComputedVar depends on, expect recalculation.
  781. Args:
  782. interdependent_state: A state with varying Var dependencies.
  783. """
  784. interdependent_state._v2 = 2
  785. assert interdependent_state.get_delta() == {
  786. interdependent_state.get_full_name(): {"v2x2": 4},
  787. }
  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. ms = MainState()
  865. ms.set_v2(1)
  866. assert ms.v == 1
  867. # ensure handler can be called from substate
  868. ms.substates[SubState.get_name()].set_v3(2)
  869. assert ms.v == 2
  870. def test_computed_var_cached():
  871. """Test that a ComputedVar doesn't recalculate when accessed."""
  872. comp_v_calls = 0
  873. class ComputedState(BaseState):
  874. v: int = 0
  875. @rx.cached_var
  876. def comp_v(self) -> int:
  877. nonlocal comp_v_calls
  878. comp_v_calls += 1
  879. return self.v
  880. cs = ComputedState()
  881. assert cs.dict()[cs.get_full_name()]["v"] == 0
  882. assert comp_v_calls == 1
  883. assert cs.dict()[cs.get_full_name()]["comp_v"] == 0
  884. assert comp_v_calls == 1
  885. assert cs.comp_v == 0
  886. assert comp_v_calls == 1
  887. cs.v = 1
  888. assert comp_v_calls == 1
  889. assert cs.comp_v == 1
  890. assert comp_v_calls == 2
  891. def test_computed_var_cached_depends_on_non_cached():
  892. """Test that a cached_var is recalculated if it depends on non-cached ComputedVar."""
  893. class ComputedState(BaseState):
  894. v: int = 0
  895. @rx.var
  896. def no_cache_v(self) -> int:
  897. return self.v
  898. @rx.cached_var
  899. def dep_v(self) -> int:
  900. return self.no_cache_v # type: ignore
  901. @rx.cached_var
  902. def comp_v(self) -> int:
  903. return self.v
  904. cs = ComputedState()
  905. assert cs.dirty_vars == set()
  906. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  907. cs._clean()
  908. assert cs.dirty_vars == set()
  909. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  910. cs._clean()
  911. assert cs.dirty_vars == set()
  912. cs.v = 1
  913. assert cs.dirty_vars == {"v", "comp_v", "dep_v", "no_cache_v"}
  914. assert cs.get_delta() == {
  915. cs.get_name(): {"v": 1, "no_cache_v": 1, "dep_v": 1, "comp_v": 1}
  916. }
  917. cs._clean()
  918. assert cs.dirty_vars == set()
  919. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  920. cs._clean()
  921. assert cs.dirty_vars == set()
  922. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  923. cs._clean()
  924. assert cs.dirty_vars == set()
  925. def test_computed_var_depends_on_parent_non_cached():
  926. """Child state cached_var that depends on parent state un cached var is always recalculated."""
  927. counter = 0
  928. class ParentState(BaseState):
  929. @rx.var
  930. def no_cache_v(self) -> int:
  931. nonlocal counter
  932. counter += 1
  933. return counter
  934. class ChildState(ParentState):
  935. @rx.cached_var
  936. def dep_v(self) -> int:
  937. return self.no_cache_v # type: ignore
  938. ps = ParentState()
  939. cs = ps.substates[ChildState.get_name()]
  940. assert ps.dirty_vars == set()
  941. assert cs.dirty_vars == set()
  942. dict1 = ps.dict()
  943. assert dict1[ps.get_full_name()] == {
  944. "no_cache_v": 1,
  945. "router": formatted_router,
  946. }
  947. assert dict1[cs.get_full_name()] == {"dep_v": 2}
  948. dict2 = ps.dict()
  949. assert dict2[ps.get_full_name()] == {
  950. "no_cache_v": 3,
  951. "router": formatted_router,
  952. }
  953. assert dict2[cs.get_full_name()] == {"dep_v": 4}
  954. dict3 = ps.dict()
  955. assert dict3[ps.get_full_name()] == {
  956. "no_cache_v": 5,
  957. "router": formatted_router,
  958. }
  959. assert dict3[cs.get_full_name()] == {"dep_v": 6}
  960. assert counter == 6
  961. @pytest.mark.parametrize("use_partial", [True, False])
  962. def test_cached_var_depends_on_event_handler(use_partial: bool):
  963. """A cached_var that calls an event handler calculates deps correctly.
  964. Args:
  965. use_partial: if true, replace the EventHandler with functools.partial
  966. """
  967. counter = 0
  968. class HandlerState(BaseState):
  969. x: int = 42
  970. def handler(self):
  971. self.x = self.x + 1
  972. @rx.cached_var
  973. def cached_x_side_effect(self) -> int:
  974. self.handler()
  975. nonlocal counter
  976. counter += 1
  977. return counter
  978. if use_partial:
  979. HandlerState.handler = functools.partial(HandlerState.handler.fn)
  980. assert isinstance(HandlerState.handler, functools.partial)
  981. else:
  982. assert isinstance(HandlerState.handler, EventHandler)
  983. s = HandlerState()
  984. assert "cached_x_side_effect" in s._computed_var_dependencies["x"]
  985. assert s.cached_x_side_effect == 1
  986. assert s.x == 43
  987. s.handler()
  988. assert s.cached_x_side_effect == 2
  989. assert s.x == 45
  990. def test_computed_var_dependencies():
  991. """Test that a ComputedVar correctly tracks its dependencies."""
  992. class ComputedState(BaseState):
  993. v: int = 0
  994. w: int = 0
  995. x: int = 0
  996. y: List[int] = [1, 2, 3]
  997. _z: List[int] = [1, 2, 3]
  998. @rx.cached_var
  999. def comp_v(self) -> int:
  1000. """Direct access.
  1001. Returns:
  1002. The value of self.v.
  1003. """
  1004. return self.v
  1005. @rx.cached_var
  1006. def comp_w(self):
  1007. """Nested lambda.
  1008. Returns:
  1009. A lambda that returns the value of self.w.
  1010. """
  1011. return lambda: self.w
  1012. @rx.cached_var
  1013. def comp_x(self):
  1014. """Nested function.
  1015. Returns:
  1016. A function that returns the value of self.x.
  1017. """
  1018. def _():
  1019. return self.x
  1020. return _
  1021. @rx.cached_var
  1022. def comp_y(self) -> List[int]:
  1023. """Comprehension iterating over attribute.
  1024. Returns:
  1025. A list of the values of self.y.
  1026. """
  1027. return [round(y) for y in self.y]
  1028. @rx.cached_var
  1029. def comp_z(self) -> List[bool]:
  1030. """Comprehension accesses attribute.
  1031. Returns:
  1032. A list of whether the values 0-4 are in self._z.
  1033. """
  1034. return [z in self._z for z in range(5)]
  1035. cs = ComputedState()
  1036. assert cs._computed_var_dependencies["v"] == {"comp_v"}
  1037. assert cs._computed_var_dependencies["w"] == {"comp_w"}
  1038. assert cs._computed_var_dependencies["x"] == {"comp_x"}
  1039. assert cs._computed_var_dependencies["y"] == {"comp_y"}
  1040. assert cs._computed_var_dependencies["_z"] == {"comp_z"}
  1041. def test_backend_method():
  1042. """A method with leading underscore should be callable from event handler."""
  1043. class BackendMethodState(BaseState):
  1044. def _be_method(self):
  1045. return True
  1046. def handler(self):
  1047. assert self._be_method()
  1048. bms = BackendMethodState()
  1049. bms.handler()
  1050. assert bms._be_method()
  1051. def test_setattr_of_mutable_types(mutable_state):
  1052. """Test that mutable types are converted to corresponding Reflex wrappers.
  1053. Args:
  1054. mutable_state: A test state.
  1055. """
  1056. array = mutable_state.array
  1057. hashmap = mutable_state.hashmap
  1058. test_set = mutable_state.test_set
  1059. assert isinstance(array, MutableProxy)
  1060. assert isinstance(array, list)
  1061. assert isinstance(array[1], MutableProxy)
  1062. assert isinstance(array[1], list)
  1063. assert isinstance(array[2], MutableProxy)
  1064. assert isinstance(array[2], dict)
  1065. assert isinstance(hashmap, MutableProxy)
  1066. assert isinstance(hashmap, dict)
  1067. assert isinstance(hashmap["key"], MutableProxy)
  1068. assert isinstance(hashmap["key"], list)
  1069. assert isinstance(hashmap["third_key"], MutableProxy)
  1070. assert isinstance(hashmap["third_key"], dict)
  1071. assert isinstance(test_set, MutableProxy)
  1072. assert isinstance(test_set, set)
  1073. assert isinstance(mutable_state.custom, MutableProxy)
  1074. assert isinstance(mutable_state.custom.array, MutableProxy)
  1075. assert isinstance(mutable_state.custom.array, list)
  1076. assert isinstance(mutable_state.custom.hashmap, MutableProxy)
  1077. assert isinstance(mutable_state.custom.hashmap, dict)
  1078. assert isinstance(mutable_state.custom.test_set, MutableProxy)
  1079. assert isinstance(mutable_state.custom.test_set, set)
  1080. assert isinstance(mutable_state.custom.custom, MutableProxy)
  1081. mutable_state.reassign_mutables()
  1082. array = mutable_state.array
  1083. hashmap = mutable_state.hashmap
  1084. test_set = mutable_state.test_set
  1085. assert isinstance(array, MutableProxy)
  1086. assert isinstance(array, list)
  1087. assert isinstance(array[1], MutableProxy)
  1088. assert isinstance(array[1], list)
  1089. assert isinstance(array[2], MutableProxy)
  1090. assert isinstance(array[2], dict)
  1091. assert isinstance(hashmap, MutableProxy)
  1092. assert isinstance(hashmap, dict)
  1093. assert isinstance(hashmap["mod_key"], MutableProxy)
  1094. assert isinstance(hashmap["mod_key"], list)
  1095. assert isinstance(hashmap["mod_third_key"], MutableProxy)
  1096. assert isinstance(hashmap["mod_third_key"], dict)
  1097. assert isinstance(test_set, MutableProxy)
  1098. assert isinstance(test_set, set)
  1099. def test_error_on_state_method_shadow():
  1100. """Test that an error is thrown when an event handler shadows a state method."""
  1101. with pytest.raises(NameError) as err:
  1102. class InvalidTest(BaseState):
  1103. def reset(self):
  1104. pass
  1105. assert (
  1106. err.value.args[0]
  1107. == f"The event handler name `reset` shadows a builtin State method; use a different name instead"
  1108. )
  1109. @pytest.mark.asyncio
  1110. async def test_state_with_invalid_yield(capsys):
  1111. """Test that an error is thrown when a state yields an invalid value.
  1112. Args:
  1113. capsys: Pytest fixture for capture standard streams.
  1114. """
  1115. class StateWithInvalidYield(BaseState):
  1116. """A state that yields an invalid value."""
  1117. def invalid_handler(self):
  1118. """Invalid handler.
  1119. Yields:
  1120. an invalid value.
  1121. """
  1122. yield 1
  1123. invalid_state = StateWithInvalidYield()
  1124. async for update in invalid_state._process(
  1125. rx.event.Event(token="fake_token", name="invalid_handler")
  1126. ):
  1127. assert not update.delta
  1128. assert update.events == rx.event.fix_events(
  1129. [rx.window_alert("An error occurred. See logs for details.")],
  1130. token="",
  1131. )
  1132. captured = capsys.readouterr()
  1133. assert "must only return/yield: None, Events or other EventHandlers" in captured.out
  1134. @pytest.fixture(scope="function", params=["in_process", "redis"])
  1135. def state_manager(request) -> Generator[StateManager, None, None]:
  1136. """Instance of state manager parametrized for redis and in-process.
  1137. Args:
  1138. request: pytest request object.
  1139. Yields:
  1140. A state manager instance
  1141. """
  1142. state_manager = StateManager.create(state=TestState)
  1143. if request.param == "redis":
  1144. if not isinstance(state_manager, StateManagerRedis):
  1145. pytest.skip("Test requires redis")
  1146. else:
  1147. # explicitly NOT using redis
  1148. state_manager = StateManagerMemory(state=TestState)
  1149. assert not state_manager._states_locks
  1150. yield state_manager
  1151. if isinstance(state_manager, StateManagerRedis):
  1152. asyncio.get_event_loop().run_until_complete(state_manager.close())
  1153. @pytest.fixture()
  1154. def substate_token(state_manager, token):
  1155. """A token + substate name for looking up in state manager.
  1156. Args:
  1157. state_manager: A state manager instance.
  1158. token: A token.
  1159. Returns:
  1160. Token concatenated with the state_manager's state full_name.
  1161. """
  1162. return _substate_key(token, state_manager.state)
  1163. @pytest.mark.asyncio
  1164. async def test_state_manager_modify_state(
  1165. state_manager: StateManager, token: str, substate_token: str
  1166. ):
  1167. """Test that the state manager can modify a state exclusively.
  1168. Args:
  1169. state_manager: A state manager instance.
  1170. token: A token.
  1171. substate_token: A token + substate name for looking up in state manager.
  1172. """
  1173. async with state_manager.modify_state(substate_token) as state:
  1174. if isinstance(state_manager, StateManagerRedis):
  1175. assert await state_manager.redis.get(f"{token}_lock")
  1176. elif isinstance(state_manager, StateManagerMemory):
  1177. assert token in state_manager._states_locks
  1178. assert state_manager._states_locks[token].locked()
  1179. # Should be able to write proxy objects inside mutables
  1180. complex_1 = state.complex[1]
  1181. assert isinstance(complex_1, MutableProxy)
  1182. state.complex[3] = complex_1
  1183. # lock should be dropped after exiting the context
  1184. if isinstance(state_manager, StateManagerRedis):
  1185. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1186. elif isinstance(state_manager, StateManagerMemory):
  1187. assert not state_manager._states_locks[token].locked()
  1188. # separate instances should NOT share locks
  1189. sm2 = StateManagerMemory(state=TestState)
  1190. assert sm2._state_manager_lock is state_manager._state_manager_lock
  1191. assert not sm2._states_locks
  1192. if state_manager._states_locks:
  1193. assert sm2._states_locks != state_manager._states_locks
  1194. @pytest.mark.asyncio
  1195. async def test_state_manager_contend(
  1196. state_manager: StateManager, token: str, substate_token: str
  1197. ):
  1198. """Multiple coroutines attempting to access the same state.
  1199. Args:
  1200. state_manager: A state manager instance.
  1201. token: A token.
  1202. substate_token: A token + substate name for looking up in state manager.
  1203. """
  1204. n_coroutines = 10
  1205. exp_num1 = 10
  1206. async with state_manager.modify_state(substate_token) as state:
  1207. state.num1 = 0
  1208. async def _coro():
  1209. async with state_manager.modify_state(substate_token) as state:
  1210. await asyncio.sleep(0.01)
  1211. state.num1 += 1
  1212. tasks = [asyncio.create_task(_coro()) for _ in range(n_coroutines)]
  1213. for f in asyncio.as_completed(tasks):
  1214. await f
  1215. assert (await state_manager.get_state(substate_token)).num1 == exp_num1
  1216. if isinstance(state_manager, StateManagerRedis):
  1217. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1218. elif isinstance(state_manager, StateManagerMemory):
  1219. assert token in state_manager._states_locks
  1220. assert not state_manager._states_locks[token].locked()
  1221. @pytest.fixture(scope="function")
  1222. def state_manager_redis() -> Generator[StateManager, None, None]:
  1223. """Instance of state manager for redis only.
  1224. Yields:
  1225. A state manager instance
  1226. """
  1227. state_manager = StateManager.create(TestState)
  1228. if not isinstance(state_manager, StateManagerRedis):
  1229. pytest.skip("Test requires redis")
  1230. yield state_manager
  1231. asyncio.get_event_loop().run_until_complete(state_manager.close())
  1232. @pytest.fixture()
  1233. def substate_token_redis(state_manager_redis, token):
  1234. """A token + substate name for looking up in state manager.
  1235. Args:
  1236. state_manager_redis: A state manager instance.
  1237. token: A token.
  1238. Returns:
  1239. Token concatenated with the state_manager's state full_name.
  1240. """
  1241. return _substate_key(token, state_manager_redis.state)
  1242. @pytest.mark.asyncio
  1243. async def test_state_manager_lock_expire(
  1244. state_manager_redis: StateManager, token: str, substate_token_redis: str
  1245. ):
  1246. """Test that the state manager lock expires and raises exception exiting context.
  1247. Args:
  1248. state_manager_redis: A state manager instance.
  1249. token: A token.
  1250. substate_token_redis: A token + substate name for looking up in state manager.
  1251. """
  1252. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1253. async with state_manager_redis.modify_state(substate_token_redis):
  1254. await asyncio.sleep(0.01)
  1255. with pytest.raises(LockExpiredError):
  1256. async with state_manager_redis.modify_state(substate_token_redis):
  1257. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1258. @pytest.mark.asyncio
  1259. async def test_state_manager_lock_expire_contend(
  1260. state_manager_redis: StateManager, token: str, substate_token_redis: str
  1261. ):
  1262. """Test that the state manager lock expires and queued waiters proceed.
  1263. Args:
  1264. state_manager_redis: A state manager instance.
  1265. token: A token.
  1266. substate_token_redis: A token + substate name for looking up in state manager.
  1267. """
  1268. exp_num1 = 4252
  1269. unexp_num1 = 666
  1270. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1271. order = []
  1272. async def _coro_blocker():
  1273. async with state_manager_redis.modify_state(substate_token_redis) as state:
  1274. order.append("blocker")
  1275. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1276. state.num1 = unexp_num1
  1277. async def _coro_waiter():
  1278. while "blocker" not in order:
  1279. await asyncio.sleep(0.005)
  1280. async with state_manager_redis.modify_state(substate_token_redis) as state:
  1281. order.append("waiter")
  1282. assert state.num1 != unexp_num1
  1283. state.num1 = exp_num1
  1284. tasks = [
  1285. asyncio.create_task(_coro_blocker()),
  1286. asyncio.create_task(_coro_waiter()),
  1287. ]
  1288. with pytest.raises(LockExpiredError):
  1289. await tasks[0]
  1290. await tasks[1]
  1291. assert order == ["blocker", "waiter"]
  1292. assert (await state_manager_redis.get_state(substate_token_redis)).num1 == exp_num1
  1293. @pytest.fixture(scope="function")
  1294. def mock_app(monkeypatch, state_manager: StateManager) -> rx.App:
  1295. """Mock app fixture.
  1296. Args:
  1297. monkeypatch: Pytest monkeypatch object.
  1298. state_manager: A state manager.
  1299. Returns:
  1300. The app, after mocking out prerequisites.get_app()
  1301. """
  1302. app = App(state=TestState)
  1303. app_module = Mock()
  1304. setattr(app_module, CompileVars.APP, app)
  1305. app.state = TestState
  1306. app._state_manager = state_manager
  1307. app.event_namespace.emit = AsyncMock() # type: ignore
  1308. def _mock_get_app(*args, **kwargs):
  1309. return app_module
  1310. monkeypatch.setattr(prerequisites, "get_app", _mock_get_app)
  1311. return app
  1312. @pytest.mark.asyncio
  1313. async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
  1314. """Test that the state proxy works.
  1315. Args:
  1316. grandchild_state: A grandchild state.
  1317. mock_app: An app that will be returned by `get_app()`
  1318. """
  1319. child_state = grandchild_state.parent_state
  1320. assert child_state is not None
  1321. parent_state = child_state.parent_state
  1322. assert parent_state is not None
  1323. if isinstance(mock_app.state_manager, StateManagerMemory):
  1324. mock_app.state_manager.states[parent_state.get_token()] = parent_state
  1325. sp = StateProxy(grandchild_state)
  1326. assert sp.__wrapped__ == grandchild_state
  1327. assert sp._self_substate_path == grandchild_state.get_full_name().split(".")
  1328. assert sp._self_app is mock_app
  1329. assert not sp._self_mutable
  1330. assert sp._self_actx is None
  1331. # cannot use normal contextmanager protocol
  1332. with pytest.raises(TypeError), sp:
  1333. pass
  1334. with pytest.raises(ImmutableStateError):
  1335. # cannot directly modify state proxy outside of async context
  1336. sp.value2 = "16"
  1337. with pytest.raises(ImmutableStateError):
  1338. # Cannot get_state
  1339. await sp.get_state(ChildState)
  1340. with pytest.raises(ImmutableStateError):
  1341. # Cannot access get_substate
  1342. sp.get_substate([])
  1343. with pytest.raises(ImmutableStateError):
  1344. # Cannot access parent state
  1345. sp.parent_state.get_name()
  1346. with pytest.raises(ImmutableStateError):
  1347. # Cannot access substates
  1348. sp.substates[""]
  1349. async with sp:
  1350. assert sp._self_actx is not None
  1351. assert sp._self_mutable # proxy is mutable inside context
  1352. if isinstance(mock_app.state_manager, StateManagerMemory):
  1353. # For in-process store, only one instance of the state exists
  1354. assert sp.__wrapped__ is grandchild_state
  1355. else:
  1356. # When redis is used, a new+updated instance is assigned to the proxy
  1357. assert sp.__wrapped__ is not grandchild_state
  1358. sp.value2 = "42"
  1359. assert not sp._self_mutable # proxy is not mutable after exiting context
  1360. assert sp._self_actx is None
  1361. assert sp.value2 == "42"
  1362. # Get the state from the state manager directly and check that the value is updated
  1363. gotten_state = await mock_app.state_manager.get_state(
  1364. _substate_key(grandchild_state.router.session.client_token, grandchild_state)
  1365. )
  1366. if isinstance(mock_app.state_manager, StateManagerMemory):
  1367. # For in-process store, only one instance of the state exists
  1368. assert gotten_state is parent_state
  1369. else:
  1370. assert gotten_state is not parent_state
  1371. gotten_grandchild_state = gotten_state.get_substate(sp._self_substate_path)
  1372. assert gotten_grandchild_state is not None
  1373. assert gotten_grandchild_state.value2 == "42"
  1374. # ensure state update was emitted
  1375. assert mock_app.event_namespace is not None
  1376. mock_app.event_namespace.emit.assert_called_once()
  1377. mcall = mock_app.event_namespace.emit.mock_calls[0]
  1378. assert mcall.args[0] == str(SocketEvent.EVENT)
  1379. assert json.loads(mcall.args[1]) == StateUpdate(
  1380. delta={
  1381. parent_state.get_full_name(): {
  1382. "upper": "",
  1383. "sum": 3.14,
  1384. },
  1385. grandchild_state.get_full_name(): {
  1386. "value2": "42",
  1387. },
  1388. GrandchildState3.get_full_name(): {
  1389. "computed": "",
  1390. },
  1391. }
  1392. )
  1393. assert mcall.kwargs["to"] == grandchild_state.get_sid()
  1394. class BackgroundTaskState(BaseState):
  1395. """A state with a background task."""
  1396. order: List[str] = []
  1397. dict_list: Dict[str, List[int]] = {"foo": [1, 2, 3]}
  1398. @rx.var
  1399. def computed_order(self) -> List[str]:
  1400. """Get the order as a computed var.
  1401. Returns:
  1402. The value of 'order' var.
  1403. """
  1404. return self.order
  1405. @rx.background
  1406. async def background_task(self):
  1407. """A background task that updates the state."""
  1408. async with self:
  1409. assert not self.order
  1410. self.order.append("background_task:start")
  1411. assert isinstance(self, StateProxy)
  1412. with pytest.raises(ImmutableStateError):
  1413. self.order.append("bad idea")
  1414. with pytest.raises(ImmutableStateError):
  1415. # Even nested access to mutables raises an exception.
  1416. self.dict_list["foo"].append(42)
  1417. with pytest.raises(ImmutableStateError):
  1418. # Direct calling another handler that modifies state raises an exception.
  1419. self.other()
  1420. with pytest.raises(ImmutableStateError):
  1421. # Calling other methods that modify state raises an exception.
  1422. self._private_method()
  1423. # wait for some other event to happen
  1424. while len(self.order) == 1:
  1425. await asyncio.sleep(0.01)
  1426. async with self:
  1427. pass # update proxy instance
  1428. async with self:
  1429. # Methods on ImmutableMutableProxy should return their wrapped return value.
  1430. assert self.dict_list.pop("foo") == [1, 2, 3]
  1431. self.order.append("background_task:stop")
  1432. self.other() # direct calling event handlers works in context
  1433. self._private_method()
  1434. @rx.background
  1435. async def background_task_reset(self):
  1436. """A background task that resets the state."""
  1437. with pytest.raises(ImmutableStateError):
  1438. # Resetting the state should be explicitly blocked.
  1439. self.reset()
  1440. async with self:
  1441. self.order.append("foo")
  1442. self.reset()
  1443. assert not self.order
  1444. async with self:
  1445. self.order.append("reset")
  1446. @rx.background
  1447. async def background_task_generator(self):
  1448. """A background task generator that does nothing.
  1449. Yields:
  1450. None
  1451. """
  1452. yield
  1453. def other(self):
  1454. """Some other event that updates the state."""
  1455. self.order.append("other")
  1456. def _private_method(self):
  1457. """Some private method that updates the state."""
  1458. self.order.append("private")
  1459. async def bad_chain1(self):
  1460. """Test that a background task cannot be chained."""
  1461. await self.background_task()
  1462. async def bad_chain2(self):
  1463. """Test that a background task generator cannot be chained."""
  1464. async for _foo in self.background_task_generator():
  1465. pass
  1466. @pytest.mark.asyncio
  1467. async def test_background_task_no_block(mock_app: rx.App, token: str):
  1468. """Test that a background task does not block other events.
  1469. Args:
  1470. mock_app: An app that will be returned by `get_app()`
  1471. token: A token.
  1472. """
  1473. router_data = {"query": {}}
  1474. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1475. async for update in rx.app.process( # type: ignore
  1476. mock_app,
  1477. Event(
  1478. token=token,
  1479. name=f"{BackgroundTaskState.get_name()}.background_task",
  1480. router_data=router_data,
  1481. payload={},
  1482. ),
  1483. sid="",
  1484. headers={},
  1485. client_ip="",
  1486. ):
  1487. # background task returns empty update immediately
  1488. assert update == StateUpdate()
  1489. # wait for the coroutine to start
  1490. await asyncio.sleep(0.5 if CI else 0.1)
  1491. assert len(mock_app.background_tasks) == 1
  1492. # Process another normal event
  1493. async for update in rx.app.process( # type: ignore
  1494. mock_app,
  1495. Event(
  1496. token=token,
  1497. name=f"{BackgroundTaskState.get_name()}.other",
  1498. router_data=router_data,
  1499. payload={},
  1500. ),
  1501. sid="",
  1502. headers={},
  1503. client_ip="",
  1504. ):
  1505. # other task returns delta
  1506. assert update == StateUpdate(
  1507. delta={
  1508. BackgroundTaskState.get_name(): {
  1509. "order": [
  1510. "background_task:start",
  1511. "other",
  1512. ],
  1513. "computed_order": [
  1514. "background_task:start",
  1515. "other",
  1516. ],
  1517. }
  1518. }
  1519. )
  1520. # Explicit wait for background tasks
  1521. for task in tuple(mock_app.background_tasks):
  1522. await task
  1523. assert not mock_app.background_tasks
  1524. exp_order = [
  1525. "background_task:start",
  1526. "other",
  1527. "background_task:stop",
  1528. "other",
  1529. "private",
  1530. ]
  1531. assert (
  1532. await mock_app.state_manager.get_state(
  1533. _substate_key(token, BackgroundTaskState)
  1534. )
  1535. ).order == exp_order
  1536. assert mock_app.event_namespace is not None
  1537. emit_mock = mock_app.event_namespace.emit
  1538. first_ws_message = json.loads(emit_mock.mock_calls[0].args[1])
  1539. assert first_ws_message["delta"]["background_task_state"].pop("router") is not None
  1540. assert first_ws_message == {
  1541. "delta": {
  1542. "background_task_state": {
  1543. "order": ["background_task:start"],
  1544. "computed_order": ["background_task:start"],
  1545. }
  1546. },
  1547. "events": [],
  1548. "final": True,
  1549. }
  1550. for call in emit_mock.mock_calls[1:5]:
  1551. assert json.loads(call.args[1]) == {
  1552. "delta": {
  1553. "background_task_state": {"computed_order": ["background_task:start"]}
  1554. },
  1555. "events": [],
  1556. "final": True,
  1557. }
  1558. assert json.loads(emit_mock.mock_calls[-2].args[1]) == {
  1559. "delta": {
  1560. "background_task_state": {
  1561. "order": exp_order,
  1562. "computed_order": exp_order,
  1563. "dict_list": {},
  1564. }
  1565. },
  1566. "events": [],
  1567. "final": True,
  1568. }
  1569. assert json.loads(emit_mock.mock_calls[-1].args[1]) == {
  1570. "delta": {
  1571. "background_task_state": {
  1572. "computed_order": exp_order,
  1573. },
  1574. },
  1575. "events": [],
  1576. "final": True,
  1577. }
  1578. @pytest.mark.asyncio
  1579. async def test_background_task_reset(mock_app: rx.App, token: str):
  1580. """Test that a background task calling reset is protected by the state proxy.
  1581. Args:
  1582. mock_app: An app that will be returned by `get_app()`
  1583. token: A token.
  1584. """
  1585. router_data = {"query": {}}
  1586. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1587. async for update in rx.app.process( # type: ignore
  1588. mock_app,
  1589. Event(
  1590. token=token,
  1591. name=f"{BackgroundTaskState.get_name()}.background_task_reset",
  1592. router_data=router_data,
  1593. payload={},
  1594. ),
  1595. sid="",
  1596. headers={},
  1597. client_ip="",
  1598. ):
  1599. # background task returns empty update immediately
  1600. assert update == StateUpdate()
  1601. # Explicit wait for background tasks
  1602. for task in tuple(mock_app.background_tasks):
  1603. await task
  1604. assert not mock_app.background_tasks
  1605. assert (
  1606. await mock_app.state_manager.get_state(
  1607. _substate_key(token, BackgroundTaskState)
  1608. )
  1609. ).order == [
  1610. "reset",
  1611. ]
  1612. @pytest.mark.asyncio
  1613. async def test_background_task_no_chain():
  1614. """Test that a background task cannot be chained."""
  1615. bts = BackgroundTaskState()
  1616. with pytest.raises(RuntimeError):
  1617. await bts.bad_chain1()
  1618. with pytest.raises(RuntimeError):
  1619. await bts.bad_chain2()
  1620. def test_mutable_list(mutable_state):
  1621. """Test that mutable lists are tracked correctly.
  1622. Args:
  1623. mutable_state: A test state.
  1624. """
  1625. assert not mutable_state.dirty_vars
  1626. def assert_array_dirty():
  1627. assert mutable_state.dirty_vars == {"array"}
  1628. mutable_state._clean()
  1629. assert not mutable_state.dirty_vars
  1630. # Test all list operations
  1631. mutable_state.array.append(42)
  1632. assert_array_dirty()
  1633. mutable_state.array.extend([1, 2, 3])
  1634. assert_array_dirty()
  1635. mutable_state.array.insert(0, 0)
  1636. assert_array_dirty()
  1637. mutable_state.array.pop()
  1638. assert_array_dirty()
  1639. mutable_state.array.remove(42)
  1640. assert_array_dirty()
  1641. mutable_state.array.clear()
  1642. assert_array_dirty()
  1643. mutable_state.array += [1, 2, 3]
  1644. assert_array_dirty()
  1645. mutable_state.array.reverse()
  1646. assert_array_dirty()
  1647. mutable_state.array.sort()
  1648. assert_array_dirty()
  1649. mutable_state.array[0] = 666
  1650. assert_array_dirty()
  1651. del mutable_state.array[0]
  1652. assert_array_dirty()
  1653. # Test nested list operations
  1654. mutable_state.array[0] = [1, 2, 3]
  1655. assert_array_dirty()
  1656. mutable_state.array[0].append(4)
  1657. assert_array_dirty()
  1658. assert isinstance(mutable_state.array[0], MutableProxy)
  1659. # Test proxy returned from __iter__
  1660. mutable_state.array = [{}]
  1661. assert_array_dirty()
  1662. assert isinstance(mutable_state.array[0], MutableProxy)
  1663. for item in mutable_state.array:
  1664. assert isinstance(item, MutableProxy)
  1665. item["foo"] = "bar"
  1666. assert_array_dirty()
  1667. def test_mutable_dict(mutable_state):
  1668. """Test that mutable dicts are tracked correctly.
  1669. Args:
  1670. mutable_state: A test state.
  1671. """
  1672. assert not mutable_state.dirty_vars
  1673. def assert_hashmap_dirty():
  1674. assert mutable_state.dirty_vars == {"hashmap"}
  1675. mutable_state._clean()
  1676. assert not mutable_state.dirty_vars
  1677. # Test all dict operations
  1678. mutable_state.hashmap.update({"new_key": 43})
  1679. assert_hashmap_dirty()
  1680. assert mutable_state.hashmap.setdefault("another_key", 66) == "another_value"
  1681. assert_hashmap_dirty()
  1682. assert mutable_state.hashmap.setdefault("setdefault_key", 67) == 67
  1683. assert_hashmap_dirty()
  1684. assert mutable_state.hashmap.setdefault("setdefault_key", 68) == 67
  1685. assert_hashmap_dirty()
  1686. assert mutable_state.hashmap.pop("new_key") == 43
  1687. assert_hashmap_dirty()
  1688. mutable_state.hashmap.popitem()
  1689. assert_hashmap_dirty()
  1690. mutable_state.hashmap.clear()
  1691. assert_hashmap_dirty()
  1692. mutable_state.hashmap["new_key"] = 42
  1693. assert_hashmap_dirty()
  1694. del mutable_state.hashmap["new_key"]
  1695. assert_hashmap_dirty()
  1696. if sys.version_info >= (3, 9):
  1697. mutable_state.hashmap |= {"new_key": 44}
  1698. assert_hashmap_dirty()
  1699. # Test nested dict operations
  1700. mutable_state.hashmap["array"] = []
  1701. assert_hashmap_dirty()
  1702. mutable_state.hashmap["array"].append(1)
  1703. assert_hashmap_dirty()
  1704. mutable_state.hashmap["dict"] = {}
  1705. assert_hashmap_dirty()
  1706. mutable_state.hashmap["dict"]["key"] = 42
  1707. assert_hashmap_dirty()
  1708. mutable_state.hashmap["dict"]["dict"] = {}
  1709. assert_hashmap_dirty()
  1710. mutable_state.hashmap["dict"]["dict"]["key"] = 43
  1711. assert_hashmap_dirty()
  1712. # Test proxy returned from `setdefault` and `get`
  1713. mutable_value = mutable_state.hashmap.setdefault("setdefault_mutable_key", [])
  1714. assert_hashmap_dirty()
  1715. assert mutable_value == []
  1716. assert isinstance(mutable_value, MutableProxy)
  1717. mutable_value.append("foo")
  1718. assert_hashmap_dirty()
  1719. mutable_value_other_ref = mutable_state.hashmap.get("setdefault_mutable_key")
  1720. assert isinstance(mutable_value_other_ref, MutableProxy)
  1721. assert mutable_value is not mutable_value_other_ref
  1722. assert mutable_value == mutable_value_other_ref
  1723. assert not mutable_state.dirty_vars
  1724. mutable_value_other_ref.append("bar")
  1725. assert_hashmap_dirty()
  1726. # `pop` should NOT return a proxy, because the returned value is no longer in the dict
  1727. mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key")
  1728. assert not isinstance(mutable_value_third_ref, MutableProxy)
  1729. assert_hashmap_dirty()
  1730. mutable_value_third_ref.append("baz")
  1731. assert not mutable_state.dirty_vars
  1732. # Unfortunately previous refs still will mark the state dirty... nothing doing about that
  1733. assert mutable_value.pop()
  1734. assert_hashmap_dirty()
  1735. def test_mutable_set(mutable_state):
  1736. """Test that mutable sets are tracked correctly.
  1737. Args:
  1738. mutable_state: A test state.
  1739. """
  1740. assert not mutable_state.dirty_vars
  1741. def assert_set_dirty():
  1742. assert mutable_state.dirty_vars == {"test_set"}
  1743. mutable_state._clean()
  1744. assert not mutable_state.dirty_vars
  1745. # Test all set operations
  1746. mutable_state.test_set.add(42)
  1747. assert_set_dirty()
  1748. mutable_state.test_set.update([1, 2, 3])
  1749. assert_set_dirty()
  1750. mutable_state.test_set.remove(42)
  1751. assert_set_dirty()
  1752. mutable_state.test_set.discard(3)
  1753. assert_set_dirty()
  1754. mutable_state.test_set.pop()
  1755. assert_set_dirty()
  1756. mutable_state.test_set.intersection_update([1, 2, 3])
  1757. assert_set_dirty()
  1758. mutable_state.test_set.difference_update([99])
  1759. assert_set_dirty()
  1760. mutable_state.test_set.symmetric_difference_update([102, 99])
  1761. assert_set_dirty()
  1762. mutable_state.test_set |= {1, 2, 3}
  1763. assert_set_dirty()
  1764. mutable_state.test_set &= {2, 3, 4}
  1765. assert_set_dirty()
  1766. mutable_state.test_set -= {2}
  1767. assert_set_dirty()
  1768. mutable_state.test_set ^= {42}
  1769. assert_set_dirty()
  1770. mutable_state.test_set.clear()
  1771. assert_set_dirty()
  1772. def test_mutable_custom(mutable_state):
  1773. """Test that mutable custom types derived from Base are tracked correctly.
  1774. Args:
  1775. mutable_state: A test state.
  1776. """
  1777. assert not mutable_state.dirty_vars
  1778. def assert_custom_dirty():
  1779. assert mutable_state.dirty_vars == {"custom"}
  1780. mutable_state._clean()
  1781. assert not mutable_state.dirty_vars
  1782. mutable_state.custom.foo = "bar"
  1783. assert_custom_dirty()
  1784. mutable_state.custom.array.append(42)
  1785. assert_custom_dirty()
  1786. mutable_state.custom.hashmap["key"] = 68
  1787. assert_custom_dirty()
  1788. mutable_state.custom.test_set.add(42)
  1789. assert_custom_dirty()
  1790. mutable_state.custom.custom.bar = "baz"
  1791. assert_custom_dirty()
  1792. def test_mutable_backend(mutable_state):
  1793. """Test that mutable backend vars are tracked correctly.
  1794. Args:
  1795. mutable_state: A test state.
  1796. """
  1797. assert not mutable_state.dirty_vars
  1798. def assert_custom_dirty():
  1799. assert mutable_state.dirty_vars == {"_be_custom"}
  1800. mutable_state._clean()
  1801. assert not mutable_state.dirty_vars
  1802. mutable_state._be_custom.foo = "bar"
  1803. assert_custom_dirty()
  1804. mutable_state._be_custom.array.append(42)
  1805. assert_custom_dirty()
  1806. mutable_state._be_custom.hashmap["key"] = 68
  1807. assert_custom_dirty()
  1808. mutable_state._be_custom.test_set.add(42)
  1809. assert_custom_dirty()
  1810. mutable_state._be_custom.custom.bar = "baz"
  1811. assert_custom_dirty()
  1812. @pytest.mark.parametrize(
  1813. ("copy_func",),
  1814. [
  1815. (copy.copy,),
  1816. (copy.deepcopy,),
  1817. ],
  1818. )
  1819. def test_mutable_copy(mutable_state, copy_func):
  1820. """Test that mutable types are copied correctly.
  1821. Args:
  1822. mutable_state: A test state.
  1823. copy_func: A copy function.
  1824. """
  1825. ms_copy = copy_func(mutable_state)
  1826. assert ms_copy is not mutable_state
  1827. for attr in ("array", "hashmap", "test_set", "custom"):
  1828. assert getattr(ms_copy, attr) == getattr(mutable_state, attr)
  1829. assert getattr(ms_copy, attr) is not getattr(mutable_state, attr)
  1830. ms_copy.custom.array.append(42)
  1831. assert "custom" in ms_copy.dirty_vars
  1832. if copy_func is copy.copy:
  1833. assert "custom" in mutable_state.dirty_vars
  1834. else:
  1835. assert not mutable_state.dirty_vars
  1836. @pytest.mark.parametrize(
  1837. ("copy_func",),
  1838. [
  1839. (copy.copy,),
  1840. (copy.deepcopy,),
  1841. ],
  1842. )
  1843. def test_mutable_copy_vars(mutable_state, copy_func):
  1844. """Test that mutable types are copied correctly.
  1845. Args:
  1846. mutable_state: A test state.
  1847. copy_func: A copy function.
  1848. """
  1849. for attr in ("array", "hashmap", "test_set", "custom"):
  1850. var_orig = getattr(mutable_state, attr)
  1851. var_copy = copy_func(var_orig)
  1852. assert var_orig is not var_copy
  1853. assert var_orig == var_copy
  1854. # copied vars should never be proxies, as they by definition are no longer attached to the state.
  1855. assert not isinstance(var_copy, MutableProxy)
  1856. def test_duplicate_substate_class(mocker):
  1857. mocker.patch("reflex.state.is_testing_env", lambda: False)
  1858. with pytest.raises(ValueError):
  1859. class TestState(BaseState):
  1860. pass
  1861. class ChildTestState(TestState): # type: ignore # noqa
  1862. pass
  1863. class ChildTestState(TestState): # type: ignore # noqa
  1864. pass
  1865. return TestState
  1866. class Foo(Base):
  1867. """A class containing a list of str."""
  1868. tags: List[str] = ["123", "456"]
  1869. def test_json_dumps_with_mutables():
  1870. """Test that json.dumps works with Base vars inside mutable types."""
  1871. class MutableContainsBase(BaseState):
  1872. items: List[Foo] = [Foo()]
  1873. dict_val = MutableContainsBase().dict()
  1874. assert isinstance(dict_val[MutableContainsBase.get_full_name()]["items"][0], dict)
  1875. val = json_dumps(dict_val)
  1876. f_items = '[{"tags": ["123", "456"]}]'
  1877. f_formatted_router = str(formatted_router).replace("'", '"')
  1878. assert (
  1879. val
  1880. == f'{{"{MutableContainsBase.get_full_name()}": {{"items": {f_items}, "router": {f_formatted_router}}}}}'
  1881. )
  1882. def test_reset_with_mutables():
  1883. """Calling reset should always reset fields to a copy of the defaults."""
  1884. default = [[0, 0], [0, 1], [1, 1]]
  1885. copied_default = copy.deepcopy(default)
  1886. class MutableResetState(BaseState):
  1887. items: List[List[int]] = default
  1888. instance = MutableResetState()
  1889. assert instance.items.__wrapped__ is not default # type: ignore
  1890. assert instance.items == default == copied_default
  1891. instance.items.append([3, 3])
  1892. assert instance.items != default
  1893. assert instance.items != copied_default
  1894. instance.reset()
  1895. assert instance.items.__wrapped__ is not default # type: ignore
  1896. assert instance.items == default == copied_default
  1897. instance.items.append([3, 3])
  1898. assert instance.items != default
  1899. assert instance.items != copied_default
  1900. instance.reset()
  1901. assert instance.items.__wrapped__ is not default # type: ignore
  1902. assert instance.items == default == copied_default
  1903. instance.items.append([3, 3])
  1904. assert instance.items != default
  1905. assert instance.items != copied_default
  1906. class Custom1(Base):
  1907. """A custom class with a str field."""
  1908. foo: str
  1909. class Custom2(Base):
  1910. """A custom class with a Custom1 field."""
  1911. c1: Optional[Custom1] = None
  1912. c1r: Custom1
  1913. class Custom3(Base):
  1914. """A custom class with a Custom2 field."""
  1915. c2: Optional[Custom2] = None
  1916. c2r: Custom2
  1917. def test_state_union_optional():
  1918. """Test that state can be defined with Union and Optional vars."""
  1919. class UnionState(BaseState):
  1920. int_float: Union[int, float] = 0
  1921. opt_int: Optional[int]
  1922. c3: Optional[Custom3]
  1923. c3i: Custom3 # implicitly required
  1924. c3r: Custom3 = Custom3(c2r=Custom2(c1r=Custom1(foo="")))
  1925. custom_union: Union[Custom1, Custom2, Custom3] = Custom1(foo="")
  1926. assert UnionState.c3.c2._var_name == "c3?.c2" # type: ignore
  1927. assert UnionState.c3.c2.c1._var_name == "c3?.c2?.c1" # type: ignore
  1928. assert UnionState.c3.c2.c1.foo._var_name == "c3?.c2?.c1?.foo" # type: ignore
  1929. assert UnionState.c3.c2.c1r.foo._var_name == "c3?.c2?.c1r.foo" # type: ignore
  1930. assert UnionState.c3.c2r.c1._var_name == "c3?.c2r.c1" # type: ignore
  1931. assert UnionState.c3.c2r.c1.foo._var_name == "c3?.c2r.c1?.foo" # type: ignore
  1932. assert UnionState.c3.c2r.c1r.foo._var_name == "c3?.c2r.c1r.foo" # type: ignore
  1933. assert UnionState.c3i.c2._var_name == "c3i.c2" # type: ignore
  1934. assert UnionState.c3r.c2._var_name == "c3r.c2" # type: ignore
  1935. assert UnionState.custom_union.foo is not None # type: ignore
  1936. assert UnionState.custom_union.c1 is not None # type: ignore
  1937. assert UnionState.custom_union.c1r is not None # type: ignore
  1938. assert UnionState.custom_union.c2 is not None # type: ignore
  1939. assert UnionState.custom_union.c2r is not None # type: ignore
  1940. assert types.is_optional(UnionState.opt_int._var_type) # type: ignore
  1941. assert types.is_union(UnionState.int_float._var_type) # type: ignore
  1942. def exp_is_hydrated(state: State, is_hydrated: bool = True) -> Dict[str, Any]:
  1943. """Expected IS_HYDRATED delta that would be emitted by HydrateMiddleware.
  1944. Args:
  1945. state: the State that is hydrated.
  1946. is_hydrated: whether the state is hydrated.
  1947. Returns:
  1948. dict similar to that returned by `State.get_delta` with IS_HYDRATED: is_hydrated
  1949. """
  1950. return {state.get_full_name(): {CompileVars.IS_HYDRATED: is_hydrated}}
  1951. class OnLoadState(State):
  1952. """A test state with no return in handler."""
  1953. num: int = 0
  1954. def test_handler(self):
  1955. """Test handler."""
  1956. self.num += 1
  1957. class OnLoadState2(State):
  1958. """A test state with return in handler."""
  1959. num: int = 0
  1960. name: str
  1961. def test_handler(self):
  1962. """Test handler that calls another handler.
  1963. Returns:
  1964. Chain of EventHandlers
  1965. """
  1966. self.num += 1
  1967. return self.change_name
  1968. def change_name(self):
  1969. """Test handler to change name."""
  1970. self.name = "random"
  1971. class OnLoadState3(State):
  1972. """A test state with async handler."""
  1973. num: int = 0
  1974. async def test_handler(self):
  1975. """Test handler."""
  1976. self.num += 1
  1977. @pytest.mark.asyncio
  1978. @pytest.mark.parametrize(
  1979. "test_state, expected",
  1980. [
  1981. (OnLoadState, {"on_load_state": {"num": 1}}),
  1982. (OnLoadState2, {"on_load_state2": {"num": 1}}),
  1983. (OnLoadState3, {"on_load_state3": {"num": 1}}),
  1984. ],
  1985. )
  1986. async def test_preprocess(app_module_mock, token, test_state, expected, mocker):
  1987. """Test that a state hydrate event is processed correctly.
  1988. Args:
  1989. app_module_mock: The app module that will be returned by get_app().
  1990. token: A token.
  1991. test_state: State to process event.
  1992. expected: Expected delta.
  1993. mocker: pytest mock object.
  1994. """
  1995. mocker.patch(
  1996. "reflex.state.State.class_subclasses", {test_state, OnLoadInternalState}
  1997. )
  1998. app = app_module_mock.app = App(
  1999. state=State, load_events={"index": [test_state.test_handler]}
  2000. )
  2001. state = State()
  2002. updates = []
  2003. async for update in rx.app.process(
  2004. app=app,
  2005. event=Event(
  2006. token=token,
  2007. name=f"{state.get_name()}.{CompileVars.ON_LOAD_INTERNAL}",
  2008. router_data={RouteVar.PATH: "/", RouteVar.ORIGIN: "/", RouteVar.QUERY: {}},
  2009. ),
  2010. sid="sid",
  2011. headers={},
  2012. client_ip="",
  2013. ):
  2014. assert isinstance(update, StateUpdate)
  2015. updates.append(update)
  2016. assert len(updates) == 1
  2017. assert updates[0].delta["state"].pop("router") is not None
  2018. assert updates[0].delta == exp_is_hydrated(state, False)
  2019. events = updates[0].events
  2020. assert len(events) == 2
  2021. assert (await state._process(events[0]).__anext__()).delta == {
  2022. test_state.get_full_name(): {"num": 1}
  2023. }
  2024. assert (await state._process(events[1]).__anext__()).delta == exp_is_hydrated(state)
  2025. @pytest.mark.asyncio
  2026. async def test_preprocess_multiple_load_events(app_module_mock, token, mocker):
  2027. """Test that a state hydrate event for multiple on-load events is processed correctly.
  2028. Args:
  2029. app_module_mock: The app module that will be returned by get_app().
  2030. token: A token.
  2031. mocker: pytest mock object.
  2032. """
  2033. mocker.patch(
  2034. "reflex.state.State.class_subclasses", {OnLoadState, OnLoadInternalState}
  2035. )
  2036. app = app_module_mock.app = App(
  2037. state=State,
  2038. load_events={"index": [OnLoadState.test_handler, OnLoadState.test_handler]},
  2039. )
  2040. state = State()
  2041. updates = []
  2042. async for update in rx.app.process(
  2043. app=app,
  2044. event=Event(
  2045. token=token,
  2046. name=f"{state.get_full_name()}.{CompileVars.ON_LOAD_INTERNAL}",
  2047. router_data={RouteVar.PATH: "/", RouteVar.ORIGIN: "/", RouteVar.QUERY: {}},
  2048. ),
  2049. sid="sid",
  2050. headers={},
  2051. client_ip="",
  2052. ):
  2053. assert isinstance(update, StateUpdate)
  2054. updates.append(update)
  2055. assert len(updates) == 1
  2056. assert updates[0].delta["state"].pop("router") is not None
  2057. assert updates[0].delta == exp_is_hydrated(state, False)
  2058. events = updates[0].events
  2059. assert len(events) == 3
  2060. assert (await state._process(events[0]).__anext__()).delta == {
  2061. OnLoadState.get_full_name(): {"num": 1}
  2062. }
  2063. assert (await state._process(events[1]).__anext__()).delta == {
  2064. OnLoadState.get_full_name(): {"num": 2}
  2065. }
  2066. assert (await state._process(events[2]).__anext__()).delta == exp_is_hydrated(state)
  2067. @pytest.mark.asyncio
  2068. async def test_get_state(mock_app: rx.App, token: str):
  2069. """Test that a get_state populates the top level state and delta calculation is correct.
  2070. Args:
  2071. mock_app: An app that will be returned by `get_app()`
  2072. token: A token.
  2073. """
  2074. mock_app.state_manager.state = mock_app.state = TestState
  2075. # Get instance of ChildState2.
  2076. test_state = await mock_app.state_manager.get_state(
  2077. _substate_key(token, ChildState2)
  2078. )
  2079. assert isinstance(test_state, TestState)
  2080. if isinstance(mock_app.state_manager, StateManagerMemory):
  2081. # All substates are available
  2082. assert tuple(sorted(test_state.substates)) == (
  2083. "child_state",
  2084. "child_state2",
  2085. "child_state3",
  2086. )
  2087. else:
  2088. # Sibling states are only populated if they have computed vars
  2089. assert tuple(sorted(test_state.substates)) == ("child_state2", "child_state3")
  2090. # Because ChildState3 has a computed var, it is always dirty, and always populated.
  2091. assert (
  2092. test_state.substates["child_state3"].substates["grandchild_state3"].computed
  2093. == ""
  2094. )
  2095. # Get the child_state2 directly.
  2096. child_state2_direct = test_state.get_substate(["child_state2"])
  2097. child_state2_get_state = await test_state.get_state(ChildState2)
  2098. # These should be the same object.
  2099. assert child_state2_direct is child_state2_get_state
  2100. # Get arbitrary GrandchildState.
  2101. grandchild_state = await child_state2_get_state.get_state(GrandchildState)
  2102. assert isinstance(grandchild_state, GrandchildState)
  2103. # Now the original root should have all substates populated.
  2104. assert tuple(sorted(test_state.substates)) == (
  2105. "child_state",
  2106. "child_state2",
  2107. "child_state3",
  2108. )
  2109. # ChildState should be retrievable
  2110. child_state_direct = test_state.get_substate(["child_state"])
  2111. child_state_get_state = await test_state.get_state(ChildState)
  2112. # These should be the same object.
  2113. assert child_state_direct is child_state_get_state
  2114. # GrandchildState instance should be the same as the one retrieved from the child_state2.
  2115. assert grandchild_state is child_state_direct.get_substate(["grandchild_state"])
  2116. grandchild_state.value2 = "set_value"
  2117. assert test_state.get_delta() == {
  2118. TestState.get_full_name(): {
  2119. "sum": 3.14,
  2120. "upper": "",
  2121. },
  2122. GrandchildState.get_full_name(): {
  2123. "value2": "set_value",
  2124. },
  2125. GrandchildState3.get_full_name(): {
  2126. "computed": "",
  2127. },
  2128. }
  2129. # Get a fresh instance
  2130. new_test_state = await mock_app.state_manager.get_state(
  2131. _substate_key(token, ChildState2)
  2132. )
  2133. assert isinstance(new_test_state, TestState)
  2134. if isinstance(mock_app.state_manager, StateManagerMemory):
  2135. # In memory, it's the same instance
  2136. assert new_test_state is test_state
  2137. test_state._clean()
  2138. # All substates are available
  2139. assert tuple(sorted(new_test_state.substates)) == (
  2140. "child_state",
  2141. "child_state2",
  2142. "child_state3",
  2143. )
  2144. else:
  2145. # With redis, we get a whole new instance
  2146. assert new_test_state is not test_state
  2147. # Sibling states are only populated if they have computed vars
  2148. assert tuple(sorted(new_test_state.substates)) == (
  2149. "child_state2",
  2150. "child_state3",
  2151. )
  2152. # Set a value on child_state2, should update cached var in grandchild_state2
  2153. child_state2 = new_test_state.get_substate(("child_state2",))
  2154. child_state2.value = "set_c2_value"
  2155. assert new_test_state.get_delta() == {
  2156. TestState.get_full_name(): {
  2157. "sum": 3.14,
  2158. "upper": "",
  2159. },
  2160. ChildState2.get_full_name(): {
  2161. "value": "set_c2_value",
  2162. },
  2163. GrandchildState2.get_full_name(): {
  2164. "cached": "set_c2_value",
  2165. },
  2166. GrandchildState3.get_full_name(): {
  2167. "computed": "",
  2168. },
  2169. }