test_state.py 91 KB

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