test_state.py 81 KB

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