test_state.py 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091
  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 Dict, Generator, List
  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.base import Base
  15. from reflex.constants import CompileVars, RouteVar, SocketEvent
  16. from reflex.event import Event, EventHandler
  17. from reflex.state import (
  18. ImmutableStateError,
  19. LockExpiredError,
  20. MutableProxy,
  21. State,
  22. StateManager,
  23. StateManagerMemory,
  24. StateManagerRedis,
  25. StateProxy,
  26. StateUpdate,
  27. )
  28. from reflex.utils import prerequisites
  29. from reflex.vars import BaseVar, ComputedVar
  30. from .states import GenState
  31. CI = bool(os.environ.get("CI", False))
  32. LOCK_EXPIRATION = 2000 if CI else 100
  33. LOCK_EXPIRE_SLEEP = 2.5 if CI else 0.2
  34. class Object(Base):
  35. """A test object fixture."""
  36. prop1: int = 42
  37. prop2: str = "hello"
  38. class TestState(State):
  39. """A test state."""
  40. # Set this class as not test one
  41. __test__ = False
  42. num1: int
  43. num2: float = 3.14
  44. key: str
  45. map_key: str = "a"
  46. array: List[float] = [1, 2, 3.14]
  47. mapping: Dict[str, List[int]] = {"a": [1, 2, 3], "b": [4, 5, 6]}
  48. obj: Object = Object()
  49. complex: Dict[int, Object] = {1: Object(), 2: Object()}
  50. fig: Figure = Figure()
  51. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  52. @ComputedVar
  53. def sum(self) -> float:
  54. """Dynamically sum the numbers.
  55. Returns:
  56. The sum of the numbers.
  57. """
  58. return self.num1 + self.num2
  59. @ComputedVar
  60. def upper(self) -> str:
  61. """Uppercase the key.
  62. Returns:
  63. The uppercased key.
  64. """
  65. return self.key.upper()
  66. def do_something(self):
  67. """Do something."""
  68. pass
  69. class ChildState(TestState):
  70. """A child state fixture."""
  71. value: str
  72. count: int = 23
  73. def change_both(self, value: str, count: int):
  74. """Change both the value and count.
  75. Args:
  76. value: The new value.
  77. count: The new count.
  78. """
  79. self.value = value.upper()
  80. self.count = count * 2
  81. class ChildState2(TestState):
  82. """A child state fixture."""
  83. value: str
  84. class GrandchildState(ChildState):
  85. """A grandchild state fixture."""
  86. value2: str
  87. def do_nothing(self):
  88. """Do something."""
  89. pass
  90. class DateTimeState(State):
  91. """A State with some datetime fields."""
  92. d: datetime.date = datetime.date.fromisoformat("1989-11-09")
  93. dt: datetime.datetime = datetime.datetime.fromisoformat("1989-11-09T18:53:00+01:00")
  94. t: datetime.time = datetime.time.fromisoformat("18:53:00+01:00")
  95. td: datetime.timedelta = datetime.timedelta(days=11, minutes=11)
  96. @pytest.fixture
  97. def test_state() -> TestState:
  98. """A state.
  99. Returns:
  100. A test state.
  101. """
  102. return TestState() # type: ignore
  103. @pytest.fixture
  104. def child_state(test_state) -> ChildState:
  105. """A child state.
  106. Args:
  107. test_state: A test state.
  108. Returns:
  109. A test child state.
  110. """
  111. child_state = test_state.get_substate(["child_state"])
  112. assert child_state is not None
  113. return child_state
  114. @pytest.fixture
  115. def child_state2(test_state) -> ChildState2:
  116. """A second child state.
  117. Args:
  118. test_state: A test state.
  119. Returns:
  120. A second test child state.
  121. """
  122. child_state2 = test_state.get_substate(["child_state2"])
  123. assert child_state2 is not None
  124. return child_state2
  125. @pytest.fixture
  126. def grandchild_state(child_state) -> GrandchildState:
  127. """A state.
  128. Args:
  129. child_state: A child state.
  130. Returns:
  131. A test state.
  132. """
  133. grandchild_state = child_state.get_substate(["grandchild_state"])
  134. assert grandchild_state is not None
  135. return grandchild_state
  136. def test_base_class_vars(test_state):
  137. """Test that the class vars are set correctly.
  138. Args:
  139. test_state: A state.
  140. """
  141. fields = test_state.get_fields()
  142. cls = type(test_state)
  143. for field in fields:
  144. if field in test_state.get_skip_vars():
  145. continue
  146. prop = getattr(cls, field)
  147. assert isinstance(prop, BaseVar)
  148. assert prop.name == field
  149. assert cls.num1.type_ == int
  150. assert cls.num2.type_ == float
  151. assert cls.key.type_ == str
  152. def test_computed_class_var(test_state):
  153. """Test that the class computed vars are set correctly.
  154. Args:
  155. test_state: A state.
  156. """
  157. cls = type(test_state)
  158. vars = [(prop.name, prop.type_) for prop in cls.computed_vars.values()]
  159. assert ("sum", float) in vars
  160. assert ("upper", str) in vars
  161. def test_class_vars(test_state):
  162. """Test that the class vars are set correctly.
  163. Args:
  164. test_state: A state.
  165. """
  166. cls = type(test_state)
  167. assert set(cls.vars.keys()) == {
  168. CompileVars.IS_HYDRATED, # added by hydrate_middleware to all State
  169. "num1",
  170. "num2",
  171. "key",
  172. "map_key",
  173. "array",
  174. "mapping",
  175. "obj",
  176. "complex",
  177. "sum",
  178. "upper",
  179. "fig",
  180. "dt",
  181. }
  182. def test_event_handlers(test_state):
  183. """Test that event handler is set correctly.
  184. Args:
  185. test_state: A state.
  186. """
  187. expected = {
  188. "do_something",
  189. "set_array",
  190. "set_complex",
  191. "set_fig",
  192. "set_key",
  193. "set_mapping",
  194. "set_num1",
  195. "set_num2",
  196. "set_obj",
  197. }
  198. cls = type(test_state)
  199. assert set(cls.event_handlers.keys()).intersection(expected) == expected
  200. def test_default_value(test_state):
  201. """Test that the default value of a var is correct.
  202. Args:
  203. test_state: A state.
  204. """
  205. assert test_state.num1 == 0
  206. assert test_state.num2 == 3.14
  207. assert test_state.key == ""
  208. assert test_state.sum == 3.14
  209. assert test_state.upper == ""
  210. def test_computed_vars(test_state):
  211. """Test that the computed var is computed correctly.
  212. Args:
  213. test_state: A state.
  214. """
  215. test_state.num1 = 1
  216. test_state.num2 = 4
  217. assert test_state.sum == 5
  218. test_state.key = "hello world"
  219. assert test_state.upper == "HELLO WORLD"
  220. def test_dict(test_state):
  221. """Test that the dict representation of a state is correct.
  222. Args:
  223. test_state: A state.
  224. """
  225. substates = {"child_state", "child_state2"}
  226. assert set(test_state.dict().keys()) == set(test_state.vars.keys()) | substates
  227. assert (
  228. set(test_state.dict(include_computed=False).keys())
  229. == set(test_state.base_vars) | substates
  230. )
  231. def test_default_setters(test_state):
  232. """Test that we can set default values.
  233. Args:
  234. test_state: A state.
  235. """
  236. for prop_name in test_state.base_vars:
  237. # Each base var should have a default setter.
  238. assert hasattr(test_state, f"set_{prop_name}")
  239. def test_class_indexing_with_vars():
  240. """Test that we can index into a state var with another var."""
  241. prop = TestState.array[TestState.num1]
  242. assert str(prop) == "{test_state.array.at(test_state.num1)}"
  243. prop = TestState.mapping["a"][TestState.num1]
  244. assert str(prop) == '{test_state.mapping["a"].at(test_state.num1)}'
  245. prop = TestState.mapping[TestState.map_key]
  246. assert str(prop) == "{test_state.mapping[test_state.map_key]}"
  247. def test_class_attributes():
  248. """Test that we can get class attributes."""
  249. prop = TestState.obj.prop1
  250. assert str(prop) == "{test_state.obj.prop1}"
  251. prop = TestState.complex[1].prop1
  252. assert str(prop) == "{test_state.complex[1].prop1}"
  253. def test_get_parent_state():
  254. """Test getting the parent state."""
  255. assert TestState.get_parent_state() is None
  256. assert ChildState.get_parent_state() == TestState
  257. assert ChildState2.get_parent_state() == TestState
  258. assert GrandchildState.get_parent_state() == ChildState
  259. def test_get_substates():
  260. """Test getting the substates."""
  261. assert TestState.get_substates() == {ChildState, ChildState2}
  262. assert ChildState.get_substates() == {GrandchildState}
  263. assert ChildState2.get_substates() == set()
  264. assert GrandchildState.get_substates() == set()
  265. def test_get_name():
  266. """Test getting the name of a state."""
  267. assert TestState.get_name() == "test_state"
  268. assert ChildState.get_name() == "child_state"
  269. assert ChildState2.get_name() == "child_state2"
  270. assert GrandchildState.get_name() == "grandchild_state"
  271. def test_get_full_name():
  272. """Test getting the full name."""
  273. assert TestState.get_full_name() == "test_state"
  274. assert ChildState.get_full_name() == "test_state.child_state"
  275. assert ChildState2.get_full_name() == "test_state.child_state2"
  276. assert GrandchildState.get_full_name() == "test_state.child_state.grandchild_state"
  277. def test_get_class_substate():
  278. """Test getting the substate of a class."""
  279. assert TestState.get_class_substate(("child_state",)) == ChildState
  280. assert TestState.get_class_substate(("child_state2",)) == ChildState2
  281. assert ChildState.get_class_substate(("grandchild_state",)) == GrandchildState
  282. assert (
  283. TestState.get_class_substate(("child_state", "grandchild_state"))
  284. == GrandchildState
  285. )
  286. with pytest.raises(ValueError):
  287. TestState.get_class_substate(("invalid_child",))
  288. with pytest.raises(ValueError):
  289. TestState.get_class_substate(
  290. (
  291. "child_state",
  292. "invalid_child",
  293. )
  294. )
  295. def test_get_class_var():
  296. """Test getting the var of a class."""
  297. assert TestState.get_class_var(("num1",)).equals(TestState.num1)
  298. assert TestState.get_class_var(("num2",)).equals(TestState.num2)
  299. assert ChildState.get_class_var(("value",)).equals(ChildState.value)
  300. assert GrandchildState.get_class_var(("value2",)).equals(GrandchildState.value2)
  301. assert TestState.get_class_var(("child_state", "value")).equals(ChildState.value)
  302. assert TestState.get_class_var(
  303. ("child_state", "grandchild_state", "value2")
  304. ).equals(
  305. GrandchildState.value2,
  306. )
  307. assert ChildState.get_class_var(("grandchild_state", "value2")).equals(
  308. GrandchildState.value2,
  309. )
  310. with pytest.raises(ValueError):
  311. TestState.get_class_var(("invalid_var",))
  312. with pytest.raises(ValueError):
  313. TestState.get_class_var(
  314. (
  315. "child_state",
  316. "invalid_var",
  317. )
  318. )
  319. def test_set_class_var():
  320. """Test setting the var of a class."""
  321. with pytest.raises(AttributeError):
  322. TestState.num3 # type: ignore
  323. TestState._set_var(BaseVar(name="num3", type_=int).set_state(TestState))
  324. var = TestState.num3 # type: ignore
  325. assert var.name == "num3"
  326. assert var.type_ == int
  327. assert var.state == TestState.get_full_name()
  328. def test_set_parent_and_substates(test_state, child_state, grandchild_state):
  329. """Test setting the parent and substates.
  330. Args:
  331. test_state: A state.
  332. child_state: A child state.
  333. grandchild_state: A grandchild state.
  334. """
  335. assert len(test_state.substates) == 2
  336. assert set(test_state.substates) == {"child_state", "child_state2"}
  337. assert child_state.parent_state == test_state
  338. assert len(child_state.substates) == 1
  339. assert set(child_state.substates) == {"grandchild_state"}
  340. assert grandchild_state.parent_state == child_state
  341. assert len(grandchild_state.substates) == 0
  342. def test_get_child_attribute(test_state, child_state, child_state2, grandchild_state):
  343. """Test getting the attribute of a state.
  344. Args:
  345. test_state: A state.
  346. child_state: A child state.
  347. child_state2: A child state.
  348. grandchild_state: A grandchild state.
  349. """
  350. assert test_state.num1 == 0
  351. assert child_state.value == ""
  352. assert child_state2.value == ""
  353. assert child_state.count == 23
  354. assert grandchild_state.value2 == ""
  355. with pytest.raises(AttributeError):
  356. test_state.invalid
  357. with pytest.raises(AttributeError):
  358. test_state.child_state.invalid
  359. with pytest.raises(AttributeError):
  360. test_state.child_state.grandchild_state.invalid
  361. def test_set_child_attribute(test_state, child_state, grandchild_state):
  362. """Test setting the attribute of a state.
  363. Args:
  364. test_state: A state.
  365. child_state: A child state.
  366. grandchild_state: A grandchild state.
  367. """
  368. test_state.num1 = 10
  369. assert test_state.num1 == 10
  370. assert child_state.num1 == 10
  371. assert grandchild_state.num1 == 10
  372. grandchild_state.num1 = 5
  373. assert test_state.num1 == 5
  374. assert child_state.num1 == 5
  375. assert grandchild_state.num1 == 5
  376. child_state.value = "test"
  377. assert child_state.value == "test"
  378. assert grandchild_state.value == "test"
  379. grandchild_state.value = "test2"
  380. assert child_state.value == "test2"
  381. assert grandchild_state.value == "test2"
  382. grandchild_state.value2 = "test3"
  383. assert grandchild_state.value2 == "test3"
  384. def test_get_substate(test_state, child_state, child_state2, grandchild_state):
  385. """Test getting the substate of a state.
  386. Args:
  387. test_state: A state.
  388. child_state: A child state.
  389. child_state2: A child state.
  390. grandchild_state: A grandchild state.
  391. """
  392. assert test_state.get_substate(("child_state",)) == child_state
  393. assert test_state.get_substate(("child_state2",)) == child_state2
  394. assert (
  395. test_state.get_substate(("child_state", "grandchild_state")) == grandchild_state
  396. )
  397. assert child_state.get_substate(("grandchild_state",)) == grandchild_state
  398. with pytest.raises(ValueError):
  399. test_state.get_substate(("invalid",))
  400. with pytest.raises(ValueError):
  401. test_state.get_substate(("child_state", "invalid"))
  402. with pytest.raises(ValueError):
  403. test_state.get_substate(("child_state", "grandchild_state", "invalid"))
  404. def test_set_dirty_var(test_state):
  405. """Test changing state vars marks the value as dirty.
  406. Args:
  407. test_state: A state.
  408. """
  409. # Initially there should be no dirty vars.
  410. assert test_state.dirty_vars == set()
  411. # Setting a var should mark it as dirty.
  412. test_state.num1 = 1
  413. assert test_state.dirty_vars == {"num1", "sum"}
  414. # Setting another var should mark it as dirty.
  415. test_state.num2 = 2
  416. assert test_state.dirty_vars == {"num1", "num2", "sum"}
  417. # Cleaning the state should remove all dirty vars.
  418. test_state._clean()
  419. assert test_state.dirty_vars == set()
  420. def test_set_dirty_substate(test_state, child_state, child_state2, grandchild_state):
  421. """Test changing substate vars marks the value as dirty.
  422. Args:
  423. test_state: A state.
  424. child_state: A child state.
  425. child_state2: A child state.
  426. grandchild_state: A grandchild state.
  427. """
  428. # Initially there should be no dirty vars.
  429. assert test_state.dirty_vars == set()
  430. assert child_state.dirty_vars == set()
  431. assert child_state2.dirty_vars == set()
  432. assert grandchild_state.dirty_vars == set()
  433. # Setting a var should mark it as dirty.
  434. child_state.value = "test"
  435. assert child_state.dirty_vars == {"value"}
  436. assert test_state.dirty_substates == {"child_state"}
  437. assert child_state.dirty_substates == set()
  438. # Cleaning the parent state should remove the dirty substate.
  439. test_state._clean()
  440. assert test_state.dirty_substates == set()
  441. assert child_state.dirty_vars == set()
  442. # Setting a var on the grandchild should bubble up.
  443. grandchild_state.value2 = "test2"
  444. assert child_state.dirty_substates == {"grandchild_state"}
  445. assert test_state.dirty_substates == {"child_state"}
  446. # Cleaning the middle state should keep the parent state dirty.
  447. child_state._clean()
  448. assert test_state.dirty_substates == {"child_state"}
  449. assert child_state.dirty_substates == set()
  450. assert grandchild_state.dirty_vars == set()
  451. def test_reset(test_state, child_state):
  452. """Test resetting the state.
  453. Args:
  454. test_state: A state.
  455. child_state: A child state.
  456. """
  457. # Set some values.
  458. test_state.num1 = 1
  459. test_state.num2 = 2
  460. child_state.value = "test"
  461. # Reset the state.
  462. test_state.reset()
  463. # The values should be reset.
  464. assert test_state.num1 == 0
  465. assert test_state.num2 == 3.14
  466. assert child_state.value == ""
  467. expected_dirty_vars = {
  468. "num1",
  469. "num2",
  470. "obj",
  471. "upper",
  472. "complex",
  473. "is_hydrated",
  474. "fig",
  475. "key",
  476. "sum",
  477. "array",
  478. "map_key",
  479. "mapping",
  480. "dt",
  481. }
  482. # The dirty vars should be reset.
  483. assert test_state.dirty_vars == expected_dirty_vars
  484. assert child_state.dirty_vars == {"count", "value"}
  485. # The dirty substates should be reset.
  486. assert test_state.dirty_substates == {"child_state", "child_state2"}
  487. @pytest.mark.asyncio
  488. async def test_process_event_simple(test_state):
  489. """Test processing an event.
  490. Args:
  491. test_state: A state.
  492. """
  493. assert test_state.num1 == 0
  494. event = Event(token="t", name="set_num1", payload={"value": 69})
  495. update = await test_state._process(event).__anext__()
  496. # The event should update the value.
  497. assert test_state.num1 == 69
  498. # The delta should contain the changes, including computed vars.
  499. # assert update.delta == {"test_state": {"num1": 69, "sum": 72.14}}
  500. assert update.delta == {"test_state": {"num1": 69, "sum": 72.14, "upper": ""}}
  501. assert update.events == []
  502. @pytest.mark.asyncio
  503. async def test_process_event_substate(test_state, child_state, grandchild_state):
  504. """Test processing an event on a substate.
  505. Args:
  506. test_state: A state.
  507. child_state: A child state.
  508. grandchild_state: A grandchild state.
  509. """
  510. # Events should bubble down to the substate.
  511. assert child_state.value == ""
  512. assert child_state.count == 23
  513. event = Event(
  514. token="t", name="child_state.change_both", payload={"value": "hi", "count": 12}
  515. )
  516. update = await test_state._process(event).__anext__()
  517. assert child_state.value == "HI"
  518. assert child_state.count == 24
  519. assert update.delta == {
  520. "test_state": {"sum": 3.14, "upper": ""},
  521. "test_state.child_state": {"value": "HI", "count": 24},
  522. }
  523. test_state._clean()
  524. # Test with the granchild state.
  525. assert grandchild_state.value2 == ""
  526. event = Event(
  527. token="t",
  528. name="child_state.grandchild_state.set_value2",
  529. payload={"value": "new"},
  530. )
  531. update = await test_state._process(event).__anext__()
  532. assert grandchild_state.value2 == "new"
  533. assert update.delta == {
  534. "test_state": {"sum": 3.14, "upper": ""},
  535. "test_state.child_state.grandchild_state": {"value2": "new"},
  536. }
  537. @pytest.mark.asyncio
  538. async def test_process_event_generator():
  539. """Test event handlers that generate multiple updates."""
  540. gen_state = GenState() # type: ignore
  541. event = Event(
  542. token="t",
  543. name="go",
  544. payload={"c": 5},
  545. )
  546. gen = gen_state._process(event)
  547. count = 0
  548. async for update in gen:
  549. count += 1
  550. if count == 6:
  551. assert update.delta == {}
  552. assert update.final
  553. else:
  554. assert gen_state.value == count
  555. assert update.delta == {
  556. "gen_state": {"value": count},
  557. }
  558. assert not update.final
  559. assert count == 6
  560. def test_get_token(test_state, mocker, router_data):
  561. """Test that the token obtained from the router_data is correct.
  562. Args:
  563. test_state: The test state.
  564. mocker: Pytest Mocker object.
  565. router_data: The router data fixture.
  566. """
  567. mocker.patch.object(test_state, "router_data", router_data)
  568. assert test_state.get_token() == "b181904c-3953-4a79-dc18-ae9518c22f05"
  569. def test_get_sid(test_state, mocker, router_data):
  570. """Test getting session id.
  571. Args:
  572. test_state: A state.
  573. mocker: Pytest Mocker object.
  574. router_data: The router data fixture.
  575. """
  576. mocker.patch.object(test_state, "router_data", router_data)
  577. assert test_state.get_sid() == "9fpxSzPb9aFMb4wFAAAH"
  578. def test_get_headers(test_state, mocker, router_data, router_data_headers):
  579. """Test getting client headers.
  580. Args:
  581. test_state: A state.
  582. mocker: Pytest Mocker object.
  583. router_data: The router data fixture.
  584. router_data_headers: The expected headers.
  585. """
  586. mocker.patch.object(test_state, "router_data", router_data)
  587. assert test_state.get_headers() == router_data_headers
  588. def test_get_client_ip(test_state, mocker, router_data):
  589. """Test getting client IP.
  590. Args:
  591. test_state: A state.
  592. mocker: Pytest Mocker object.
  593. router_data: The router data fixture.
  594. """
  595. mocker.patch.object(test_state, "router_data", router_data)
  596. assert test_state.get_client_ip() == "127.0.0.1"
  597. def test_get_cookies(test_state, mocker, router_data):
  598. """Test getting client cookies.
  599. Args:
  600. test_state: A state.
  601. mocker: Pytest Mocker object.
  602. router_data: The router data fixture.
  603. """
  604. mocker.patch.object(test_state, "router_data", router_data)
  605. assert test_state.get_cookies() == {
  606. "csrftoken": "mocktoken",
  607. "name": "reflex",
  608. "list_cookies": ["some", "random", "cookies"],
  609. "dict_cookies": {"name": "reflex"},
  610. "val": True,
  611. }
  612. def test_get_current_page(test_state):
  613. assert test_state.get_current_page() == ""
  614. route = "mypage/subpage"
  615. test_state.router_data = {RouteVar.PATH: route}
  616. assert test_state.get_current_page() == route
  617. def test_get_query_params(test_state):
  618. assert test_state.get_query_params() == {}
  619. params = {"p1": "a", "p2": "b"}
  620. test_state.router_data = {RouteVar.QUERY: params}
  621. assert test_state.get_query_params() == params
  622. def test_add_var():
  623. class DynamicState(State):
  624. pass
  625. ds1 = DynamicState()
  626. assert "dynamic_int" not in ds1.__dict__
  627. assert not hasattr(ds1, "dynamic_int")
  628. ds1.add_var("dynamic_int", int, 42)
  629. # Existing instances get the BaseVar
  630. assert ds1.dynamic_int.equals(DynamicState.dynamic_int) # type: ignore
  631. # New instances get an actual value with the default
  632. assert DynamicState().dynamic_int == 42
  633. ds1.add_var("dynamic_list", List[int], [5, 10])
  634. assert ds1.dynamic_list.equals(DynamicState.dynamic_list) # type: ignore
  635. ds2 = DynamicState()
  636. assert ds2.dynamic_list == [5, 10]
  637. ds2.dynamic_list.append(15)
  638. assert ds2.dynamic_list == [5, 10, 15]
  639. assert DynamicState().dynamic_list == [5, 10]
  640. ds1.add_var("dynamic_dict", Dict[str, int], {"k1": 5, "k2": 10})
  641. assert ds1.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  642. assert ds2.dynamic_dict.equals(DynamicState.dynamic_dict) # type: ignore
  643. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  644. assert DynamicState().dynamic_dict == {"k1": 5, "k2": 10}
  645. def test_add_var_default_handlers(test_state):
  646. test_state.add_var("rand_int", int, 10)
  647. assert "set_rand_int" in test_state.event_handlers
  648. assert isinstance(test_state.event_handlers["set_rand_int"], EventHandler)
  649. class InterdependentState(State):
  650. """A state with 3 vars and 3 computed vars.
  651. x: a variable that no computed var depends on
  652. v1: a varable that one computed var directly depeneds on
  653. _v2: a backend variable that one computed var directly depends on
  654. v1x2: a computed var that depends on v1
  655. v2x2: a computed var that depends on backend var _v2
  656. v1x2x2: a computed var that depends on computed var v1x2
  657. """
  658. x: int = 0
  659. v1: int = 0
  660. _v2: int = 1
  661. @rx.cached_var
  662. def v1x2(self) -> int:
  663. """Depends on var v1.
  664. Returns:
  665. Var v1 multiplied by 2
  666. """
  667. return self.v1 * 2
  668. @rx.cached_var
  669. def v2x2(self) -> int:
  670. """Depends on backend var _v2.
  671. Returns:
  672. backend var _v2 multiplied by 2
  673. """
  674. return self._v2 * 2
  675. @rx.cached_var
  676. def v1x2x2(self) -> int:
  677. """Depends on ComputedVar v1x2.
  678. Returns:
  679. ComputedVar v1x2 multiplied by 2
  680. """
  681. return self.v1x2 * 2
  682. @pytest.fixture
  683. def interdependent_state() -> State:
  684. """A state with varying dependency between vars.
  685. Returns:
  686. instance of InterdependentState
  687. """
  688. s = InterdependentState()
  689. s.dict() # prime initial relationships by accessing all ComputedVars
  690. return s
  691. def test_not_dirty_computed_var_from_var(interdependent_state):
  692. """Set Var that no ComputedVar depends on, expect no recalculation.
  693. Args:
  694. interdependent_state: A state with varying Var dependencies.
  695. """
  696. interdependent_state.x = 5
  697. assert interdependent_state.get_delta() == {
  698. interdependent_state.get_full_name(): {"x": 5},
  699. }
  700. def test_dirty_computed_var_from_var(interdependent_state):
  701. """Set Var that ComputedVar depends on, expect recalculation.
  702. The other ComputedVar depends on the changed ComputedVar and should also be
  703. recalculated. No other ComputedVars should be recalculated.
  704. Args:
  705. interdependent_state: A state with varying Var dependencies.
  706. """
  707. interdependent_state.v1 = 1
  708. assert interdependent_state.get_delta() == {
  709. interdependent_state.get_full_name(): {"v1": 1, "v1x2": 2, "v1x2x2": 4},
  710. }
  711. def test_dirty_computed_var_from_backend_var(interdependent_state):
  712. """Set backend var that ComputedVar depends on, expect recalculation.
  713. Args:
  714. interdependent_state: A state with varying Var dependencies.
  715. """
  716. interdependent_state._v2 = 2
  717. assert interdependent_state.get_delta() == {
  718. interdependent_state.get_full_name(): {"v2x2": 4},
  719. }
  720. def test_per_state_backend_var(interdependent_state):
  721. """Set backend var on one instance, expect no affect in other instances.
  722. Args:
  723. interdependent_state: A state with varying Var dependencies.
  724. """
  725. s2 = InterdependentState()
  726. assert s2._v2 == interdependent_state._v2
  727. interdependent_state._v2 = 2
  728. assert s2._v2 != interdependent_state._v2
  729. s3 = InterdependentState()
  730. assert s3._v2 != interdependent_state._v2
  731. # both s2 and s3 should still have the default value
  732. assert s2._v2 == s3._v2
  733. # changing s2._v2 should not affect others
  734. s2._v2 = 4
  735. assert s2._v2 != interdependent_state._v2
  736. assert s2._v2 != s3._v2
  737. def test_child_state():
  738. """Test that the child state computed vars can reference parent state vars."""
  739. class MainState(State):
  740. v: int = 2
  741. class ChildState(MainState):
  742. @ComputedVar
  743. def rendered_var(self):
  744. return self.v
  745. ms = MainState()
  746. cs = ms.substates[ChildState.get_name()]
  747. assert ms.v == 2
  748. assert cs.v == 2
  749. assert cs.rendered_var == 2
  750. def test_conditional_computed_vars():
  751. """Test that computed vars can have conditionals."""
  752. class MainState(State):
  753. flag: bool = False
  754. t1: str = "a"
  755. t2: str = "b"
  756. @ComputedVar
  757. def rendered_var(self) -> str:
  758. if self.flag:
  759. return self.t1
  760. return self.t2
  761. ms = MainState()
  762. # Initially there are no dirty computed vars.
  763. assert ms._dirty_computed_vars(from_vars={"flag"}) == {"rendered_var"}
  764. assert ms._dirty_computed_vars(from_vars={"t2"}) == {"rendered_var"}
  765. assert ms._dirty_computed_vars(from_vars={"t1"}) == {"rendered_var"}
  766. assert ms.computed_vars["rendered_var"].deps(objclass=MainState) == {
  767. "flag",
  768. "t1",
  769. "t2",
  770. }
  771. def test_event_handlers_convert_to_fns(test_state, child_state):
  772. """Test that when the state is initialized, event handlers are converted to fns.
  773. Args:
  774. test_state: A state with event handlers.
  775. child_state: A child state with event handlers.
  776. """
  777. # The class instances should be event handlers.
  778. assert isinstance(TestState.do_something, EventHandler)
  779. assert isinstance(ChildState.change_both, EventHandler)
  780. # The object instances should be fns.
  781. test_state.do_something()
  782. child_state.change_both(value="goose", count=9)
  783. assert child_state.value == "GOOSE"
  784. assert child_state.count == 18
  785. def test_event_handlers_call_other_handlers():
  786. """Test that event handlers can call other event handlers."""
  787. class MainState(State):
  788. v: int = 0
  789. def set_v(self, v: int):
  790. self.v = v
  791. def set_v2(self, v: int):
  792. self.set_v(v)
  793. class SubState(MainState):
  794. def set_v3(self, v: int):
  795. self.set_v2(v)
  796. ms = MainState()
  797. ms.set_v2(1)
  798. assert ms.v == 1
  799. # ensure handler can be called from substate
  800. ms.substates[SubState.get_name()].set_v3(2)
  801. assert ms.v == 2
  802. def test_computed_var_cached():
  803. """Test that a ComputedVar doesn't recalculate when accessed."""
  804. comp_v_calls = 0
  805. class ComputedState(State):
  806. v: int = 0
  807. @rx.cached_var
  808. def comp_v(self) -> int:
  809. nonlocal comp_v_calls
  810. comp_v_calls += 1
  811. return self.v
  812. cs = ComputedState()
  813. assert cs.dict()["v"] == 0
  814. assert comp_v_calls == 1
  815. assert cs.dict()["comp_v"] == 0
  816. assert comp_v_calls == 1
  817. assert cs.comp_v == 0
  818. assert comp_v_calls == 1
  819. cs.v = 1
  820. assert comp_v_calls == 1
  821. assert cs.comp_v == 1
  822. assert comp_v_calls == 2
  823. def test_computed_var_cached_depends_on_non_cached():
  824. """Test that a cached_var is recalculated if it depends on non-cached ComputedVar."""
  825. class ComputedState(State):
  826. v: int = 0
  827. @rx.var
  828. def no_cache_v(self) -> int:
  829. return self.v
  830. @rx.cached_var
  831. def dep_v(self) -> int:
  832. return self.no_cache_v
  833. @rx.cached_var
  834. def comp_v(self) -> int:
  835. return self.v
  836. cs = ComputedState()
  837. assert cs.dirty_vars == set()
  838. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  839. cs._clean()
  840. assert cs.dirty_vars == set()
  841. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 0, "dep_v": 0}}
  842. cs._clean()
  843. assert cs.dirty_vars == set()
  844. cs.v = 1
  845. assert cs.dirty_vars == {"v", "comp_v", "dep_v", "no_cache_v"}
  846. assert cs.get_delta() == {
  847. cs.get_name(): {"v": 1, "no_cache_v": 1, "dep_v": 1, "comp_v": 1}
  848. }
  849. cs._clean()
  850. assert cs.dirty_vars == set()
  851. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  852. cs._clean()
  853. assert cs.dirty_vars == set()
  854. assert cs.get_delta() == {cs.get_name(): {"no_cache_v": 1, "dep_v": 1}}
  855. cs._clean()
  856. assert cs.dirty_vars == set()
  857. def test_computed_var_depends_on_parent_non_cached():
  858. """Child state cached_var that depends on parent state un cached var is always recalculated."""
  859. counter = 0
  860. class ParentState(State):
  861. @rx.var
  862. def no_cache_v(self) -> int:
  863. nonlocal counter
  864. counter += 1
  865. return counter
  866. class ChildState(ParentState):
  867. @rx.cached_var
  868. def dep_v(self) -> int:
  869. return self.no_cache_v
  870. ps = ParentState()
  871. cs = ps.substates[ChildState.get_name()]
  872. assert ps.dirty_vars == set()
  873. assert cs.dirty_vars == set()
  874. assert ps.dict() == {
  875. cs.get_name(): {"dep_v": 2},
  876. "no_cache_v": 1,
  877. CompileVars.IS_HYDRATED: False,
  878. }
  879. assert ps.dict() == {
  880. cs.get_name(): {"dep_v": 4},
  881. "no_cache_v": 3,
  882. CompileVars.IS_HYDRATED: False,
  883. }
  884. assert ps.dict() == {
  885. cs.get_name(): {"dep_v": 6},
  886. "no_cache_v": 5,
  887. CompileVars.IS_HYDRATED: False,
  888. }
  889. assert counter == 6
  890. @pytest.mark.parametrize("use_partial", [True, False])
  891. def test_cached_var_depends_on_event_handler(use_partial: bool):
  892. """A cached_var that calls an event handler calculates deps correctly.
  893. Args:
  894. use_partial: if true, replace the EventHandler with functools.partial
  895. """
  896. counter = 0
  897. class HandlerState(State):
  898. x: int = 42
  899. def handler(self):
  900. self.x = self.x + 1
  901. @rx.cached_var
  902. def cached_x_side_effect(self) -> int:
  903. self.handler()
  904. nonlocal counter
  905. counter += 1
  906. return counter
  907. if use_partial:
  908. HandlerState.handler = functools.partial(HandlerState.handler.fn)
  909. assert isinstance(HandlerState.handler, functools.partial)
  910. else:
  911. assert isinstance(HandlerState.handler, EventHandler)
  912. s = HandlerState()
  913. assert "cached_x_side_effect" in s.computed_var_dependencies["x"]
  914. assert s.cached_x_side_effect == 1
  915. assert s.x == 43
  916. s.handler()
  917. assert s.cached_x_side_effect == 2
  918. assert s.x == 45
  919. def test_computed_var_dependencies():
  920. """Test that a ComputedVar correctly tracks its dependencies."""
  921. class ComputedState(State):
  922. v: int = 0
  923. w: int = 0
  924. x: int = 0
  925. y: List[int] = [1, 2, 3]
  926. _z: List[int] = [1, 2, 3]
  927. @rx.cached_var
  928. def comp_v(self) -> int:
  929. """Direct access.
  930. Returns:
  931. The value of self.v.
  932. """
  933. return self.v
  934. @rx.cached_var
  935. def comp_w(self):
  936. """Nested lambda.
  937. Returns:
  938. A lambda that returns the value of self.w.
  939. """
  940. return lambda: self.w
  941. @rx.cached_var
  942. def comp_x(self):
  943. """Nested function.
  944. Returns:
  945. A function that returns the value of self.x.
  946. """
  947. def _():
  948. return self.x
  949. return _
  950. @rx.cached_var
  951. def comp_y(self) -> List[int]:
  952. """Comprehension iterating over attribute.
  953. Returns:
  954. A list of the values of self.y.
  955. """
  956. return [round(y) for y in self.y]
  957. @rx.cached_var
  958. def comp_z(self) -> List[bool]:
  959. """Comprehension accesses attribute.
  960. Returns:
  961. A list of whether the values 0-4 are in self._z.
  962. """
  963. return [z in self._z for z in range(5)]
  964. cs = ComputedState()
  965. assert cs.computed_var_dependencies["v"] == {"comp_v"}
  966. assert cs.computed_var_dependencies["w"] == {"comp_w"}
  967. assert cs.computed_var_dependencies["x"] == {"comp_x"}
  968. assert cs.computed_var_dependencies["y"] == {"comp_y"}
  969. assert cs.computed_var_dependencies["_z"] == {"comp_z"}
  970. def test_backend_method():
  971. """A method with leading underscore should be callable from event handler."""
  972. class BackendMethodState(State):
  973. def _be_method(self):
  974. return True
  975. def handler(self):
  976. assert self._be_method()
  977. bms = BackendMethodState()
  978. bms.handler()
  979. assert bms._be_method()
  980. def test_setattr_of_mutable_types(mutable_state):
  981. """Test that mutable types are converted to corresponding Reflex wrappers.
  982. Args:
  983. mutable_state: A test state.
  984. """
  985. array = mutable_state.array
  986. hashmap = mutable_state.hashmap
  987. test_set = mutable_state.test_set
  988. assert isinstance(array, MutableProxy)
  989. assert isinstance(array, list)
  990. assert isinstance(array[1], MutableProxy)
  991. assert isinstance(array[1], list)
  992. assert isinstance(array[2], MutableProxy)
  993. assert isinstance(array[2], dict)
  994. assert isinstance(hashmap, MutableProxy)
  995. assert isinstance(hashmap, dict)
  996. assert isinstance(hashmap["key"], MutableProxy)
  997. assert isinstance(hashmap["key"], list)
  998. assert isinstance(hashmap["third_key"], MutableProxy)
  999. assert isinstance(hashmap["third_key"], dict)
  1000. assert isinstance(test_set, MutableProxy)
  1001. assert isinstance(test_set, set)
  1002. assert isinstance(mutable_state.custom, MutableProxy)
  1003. assert isinstance(mutable_state.custom.array, MutableProxy)
  1004. assert isinstance(mutable_state.custom.array, list)
  1005. assert isinstance(mutable_state.custom.hashmap, MutableProxy)
  1006. assert isinstance(mutable_state.custom.hashmap, dict)
  1007. assert isinstance(mutable_state.custom.test_set, MutableProxy)
  1008. assert isinstance(mutable_state.custom.test_set, set)
  1009. assert isinstance(mutable_state.custom.custom, MutableProxy)
  1010. mutable_state.reassign_mutables()
  1011. array = mutable_state.array
  1012. hashmap = mutable_state.hashmap
  1013. test_set = mutable_state.test_set
  1014. assert isinstance(array, MutableProxy)
  1015. assert isinstance(array, list)
  1016. assert isinstance(array[1], MutableProxy)
  1017. assert isinstance(array[1], list)
  1018. assert isinstance(array[2], MutableProxy)
  1019. assert isinstance(array[2], dict)
  1020. assert isinstance(hashmap, MutableProxy)
  1021. assert isinstance(hashmap, dict)
  1022. assert isinstance(hashmap["mod_key"], MutableProxy)
  1023. assert isinstance(hashmap["mod_key"], list)
  1024. assert isinstance(hashmap["mod_third_key"], MutableProxy)
  1025. assert isinstance(hashmap["mod_third_key"], dict)
  1026. assert isinstance(test_set, MutableProxy)
  1027. assert isinstance(test_set, set)
  1028. def test_error_on_state_method_shadow():
  1029. """Test that an error is thrown when an event handler shadows a state method."""
  1030. with pytest.raises(NameError) as err:
  1031. class InvalidTest(rx.State):
  1032. def reset(self):
  1033. pass
  1034. assert (
  1035. err.value.args[0]
  1036. == f"The event handler name `reset` shadows a builtin State method; use a different name instead"
  1037. )
  1038. def test_state_with_invalid_yield():
  1039. """Test that an error is thrown when a state yields an invalid value."""
  1040. class StateWithInvalidYield(rx.State):
  1041. """A state that yields an invalid value."""
  1042. def invalid_handler(self):
  1043. """Invalid handler.
  1044. Yields:
  1045. an invalid value.
  1046. """
  1047. yield 1
  1048. invalid_state = StateWithInvalidYield()
  1049. with pytest.raises(TypeError) as err:
  1050. invalid_state._check_valid(
  1051. invalid_state.event_handlers["invalid_handler"],
  1052. rx.event.Event(token="fake_token", name="invalid_handler"),
  1053. )
  1054. assert (
  1055. "must only return/yield: None, Events or other EventHandlers"
  1056. in err.value.args[0]
  1057. )
  1058. @pytest.fixture(scope="function", params=["in_process", "redis"])
  1059. def state_manager(request) -> Generator[StateManager, None, None]:
  1060. """Instance of state manager parametrized for redis and in-process.
  1061. Args:
  1062. request: pytest request object.
  1063. Yields:
  1064. A state manager instance
  1065. """
  1066. state_manager = StateManager.create(state=TestState)
  1067. if request.param == "redis":
  1068. if not isinstance(state_manager, StateManagerRedis):
  1069. pytest.skip("Test requires redis")
  1070. else:
  1071. # explicitly NOT using redis
  1072. state_manager = StateManagerMemory(state=TestState)
  1073. assert not state_manager._states_locks
  1074. yield state_manager
  1075. if isinstance(state_manager, StateManagerRedis):
  1076. asyncio.get_event_loop().run_until_complete(state_manager.redis.close())
  1077. @pytest.mark.asyncio
  1078. async def test_state_manager_modify_state(state_manager: StateManager, token: str):
  1079. """Test that the state manager can modify a state exclusively.
  1080. Args:
  1081. state_manager: A state manager instance.
  1082. token: A token.
  1083. """
  1084. async with state_manager.modify_state(token):
  1085. if isinstance(state_manager, StateManagerRedis):
  1086. assert await state_manager.redis.get(f"{token}_lock")
  1087. elif isinstance(state_manager, StateManagerMemory):
  1088. assert token in state_manager._states_locks
  1089. assert state_manager._states_locks[token].locked()
  1090. # lock should be dropped after exiting the context
  1091. if isinstance(state_manager, StateManagerRedis):
  1092. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1093. elif isinstance(state_manager, StateManagerMemory):
  1094. assert not state_manager._states_locks[token].locked()
  1095. # separate instances should NOT share locks
  1096. sm2 = StateManagerMemory(state=TestState)
  1097. assert sm2._state_manager_lock is state_manager._state_manager_lock
  1098. assert not sm2._states_locks
  1099. if state_manager._states_locks:
  1100. assert sm2._states_locks != state_manager._states_locks
  1101. @pytest.mark.asyncio
  1102. async def test_state_manager_contend(state_manager: StateManager, token: str):
  1103. """Multiple coroutines attempting to access the same state.
  1104. Args:
  1105. state_manager: A state manager instance.
  1106. token: A token.
  1107. """
  1108. n_coroutines = 10
  1109. exp_num1 = 10
  1110. async with state_manager.modify_state(token) as state:
  1111. state.num1 = 0
  1112. async def _coro():
  1113. async with state_manager.modify_state(token) as state:
  1114. await asyncio.sleep(0.01)
  1115. state.num1 += 1
  1116. tasks = [asyncio.create_task(_coro()) for _ in range(n_coroutines)]
  1117. for f in asyncio.as_completed(tasks):
  1118. await f
  1119. assert (await state_manager.get_state(token)).num1 == exp_num1
  1120. if isinstance(state_manager, StateManagerRedis):
  1121. assert (await state_manager.redis.get(f"{token}_lock")) is None
  1122. elif isinstance(state_manager, StateManagerMemory):
  1123. assert token in state_manager._states_locks
  1124. assert not state_manager._states_locks[token].locked()
  1125. @pytest.fixture(scope="function")
  1126. def state_manager_redis() -> Generator[StateManager, None, None]:
  1127. """Instance of state manager for redis only.
  1128. Yields:
  1129. A state manager instance
  1130. """
  1131. state_manager = StateManager.create(TestState)
  1132. if not isinstance(state_manager, StateManagerRedis):
  1133. pytest.skip("Test requires redis")
  1134. yield state_manager
  1135. asyncio.get_event_loop().run_until_complete(state_manager.redis.close())
  1136. @pytest.mark.asyncio
  1137. async def test_state_manager_lock_expire(state_manager_redis: StateManager, token: str):
  1138. """Test that the state manager lock expires and raises exception exiting context.
  1139. Args:
  1140. state_manager_redis: A state manager instance.
  1141. token: A token.
  1142. """
  1143. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1144. async with state_manager_redis.modify_state(token):
  1145. await asyncio.sleep(0.01)
  1146. with pytest.raises(LockExpiredError):
  1147. async with state_manager_redis.modify_state(token):
  1148. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1149. @pytest.mark.asyncio
  1150. async def test_state_manager_lock_expire_contend(
  1151. state_manager_redis: StateManager, token: str
  1152. ):
  1153. """Test that the state manager lock expires and queued waiters proceed.
  1154. Args:
  1155. state_manager_redis: A state manager instance.
  1156. token: A token.
  1157. """
  1158. exp_num1 = 4252
  1159. unexp_num1 = 666
  1160. state_manager_redis.lock_expiration = LOCK_EXPIRATION
  1161. order = []
  1162. async def _coro_blocker():
  1163. async with state_manager_redis.modify_state(token) as state:
  1164. order.append("blocker")
  1165. await asyncio.sleep(LOCK_EXPIRE_SLEEP)
  1166. state.num1 = unexp_num1
  1167. async def _coro_waiter():
  1168. while "blocker" not in order:
  1169. await asyncio.sleep(0.005)
  1170. async with state_manager_redis.modify_state(token) as state:
  1171. order.append("waiter")
  1172. assert state.num1 != unexp_num1
  1173. state.num1 = exp_num1
  1174. tasks = [
  1175. asyncio.create_task(_coro_blocker()),
  1176. asyncio.create_task(_coro_waiter()),
  1177. ]
  1178. with pytest.raises(LockExpiredError):
  1179. await tasks[0]
  1180. await tasks[1]
  1181. assert order == ["blocker", "waiter"]
  1182. assert (await state_manager_redis.get_state(token)).num1 == exp_num1
  1183. @pytest.fixture(scope="function")
  1184. def mock_app(monkeypatch, app: rx.App, state_manager: StateManager) -> rx.App:
  1185. """Mock app fixture.
  1186. Args:
  1187. monkeypatch: Pytest monkeypatch object.
  1188. app: An app.
  1189. state_manager: A state manager.
  1190. Returns:
  1191. The app, after mocking out prerequisites.get_app()
  1192. """
  1193. app_module = Mock()
  1194. setattr(app_module, CompileVars.APP, app)
  1195. app.state = TestState
  1196. app.state_manager = state_manager
  1197. assert app.event_namespace is not None
  1198. app.event_namespace.emit = AsyncMock()
  1199. monkeypatch.setattr(prerequisites, "get_app", lambda: app_module)
  1200. return app
  1201. @pytest.mark.asyncio
  1202. async def test_state_proxy(grandchild_state: GrandchildState, mock_app: rx.App):
  1203. """Test that the state proxy works.
  1204. Args:
  1205. grandchild_state: A grandchild state.
  1206. mock_app: An app that will be returned by `get_app()`
  1207. """
  1208. child_state = grandchild_state.parent_state
  1209. assert child_state is not None
  1210. parent_state = child_state.parent_state
  1211. assert parent_state is not None
  1212. if isinstance(mock_app.state_manager, StateManagerMemory):
  1213. mock_app.state_manager.states[parent_state.get_token()] = parent_state
  1214. sp = StateProxy(grandchild_state)
  1215. assert sp.__wrapped__ == grandchild_state
  1216. assert sp._self_substate_path == grandchild_state.get_full_name().split(".")
  1217. assert sp._self_app is mock_app
  1218. assert not sp._self_mutable
  1219. assert sp._self_actx is None
  1220. # cannot use normal contextmanager protocol
  1221. with pytest.raises(TypeError), sp:
  1222. pass
  1223. with pytest.raises(ImmutableStateError):
  1224. # cannot directly modify state proxy outside of async context
  1225. sp.value2 = 16
  1226. async with sp:
  1227. assert sp._self_actx is not None
  1228. assert sp._self_mutable # proxy is mutable inside context
  1229. if isinstance(mock_app.state_manager, StateManagerMemory):
  1230. # For in-process store, only one instance of the state exists
  1231. assert sp.__wrapped__ is grandchild_state
  1232. else:
  1233. # When redis is used, a new+updated instance is assigned to the proxy
  1234. assert sp.__wrapped__ is not grandchild_state
  1235. sp.value2 = 42
  1236. assert not sp._self_mutable # proxy is not mutable after exiting context
  1237. assert sp._self_actx is None
  1238. assert sp.value2 == 42
  1239. # Get the state from the state manager directly and check that the value is updated
  1240. gotten_state = await mock_app.state_manager.get_state(grandchild_state.get_token())
  1241. if isinstance(mock_app.state_manager, StateManagerMemory):
  1242. # For in-process store, only one instance of the state exists
  1243. assert gotten_state is parent_state
  1244. else:
  1245. assert gotten_state is not parent_state
  1246. gotten_grandchild_state = gotten_state.get_substate(sp._self_substate_path)
  1247. assert gotten_grandchild_state is not None
  1248. assert gotten_grandchild_state.value2 == 42
  1249. # ensure state update was emitted
  1250. assert mock_app.event_namespace is not None
  1251. mock_app.event_namespace.emit.assert_called_once()
  1252. mcall = mock_app.event_namespace.emit.mock_calls[0]
  1253. assert mcall.args[0] == str(SocketEvent.EVENT)
  1254. assert json.loads(mcall.args[1]) == StateUpdate(
  1255. delta={
  1256. parent_state.get_full_name(): {
  1257. "upper": "",
  1258. "sum": 3.14,
  1259. },
  1260. grandchild_state.get_full_name(): {
  1261. "value2": 42,
  1262. },
  1263. }
  1264. )
  1265. assert mcall.kwargs["to"] == grandchild_state.get_sid()
  1266. class BackgroundTaskState(State):
  1267. """A state with a background task."""
  1268. order: List[str] = []
  1269. dict_list: Dict[str, List[int]] = {"foo": []}
  1270. @rx.background
  1271. async def background_task(self):
  1272. """A background task that updates the state."""
  1273. async with self:
  1274. assert not self.order
  1275. self.order.append("background_task:start")
  1276. assert isinstance(self, StateProxy)
  1277. with pytest.raises(ImmutableStateError):
  1278. self.order.append("bad idea")
  1279. with pytest.raises(ImmutableStateError):
  1280. # Even nested access to mutables raises an exception.
  1281. self.dict_list["foo"].append(42)
  1282. with pytest.raises(ImmutableStateError):
  1283. # Direct calling another handler that modifies state raises an exception.
  1284. self.other()
  1285. with pytest.raises(ImmutableStateError):
  1286. # Calling other methods that modify state raises an exception.
  1287. self._private_method()
  1288. # wait for some other event to happen
  1289. while len(self.order) == 1:
  1290. await asyncio.sleep(0.01)
  1291. async with self:
  1292. pass # update proxy instance
  1293. async with self:
  1294. self.order.append("background_task:stop")
  1295. self.other() # direct calling event handlers works in context
  1296. self._private_method()
  1297. @rx.background
  1298. async def background_task_reset(self):
  1299. """A background task that resets the state."""
  1300. with pytest.raises(ImmutableStateError):
  1301. # Resetting the state should be explicitly blocked.
  1302. self.reset()
  1303. async with self:
  1304. self.order.append("foo")
  1305. self.reset()
  1306. assert not self.order
  1307. async with self:
  1308. self.order.append("reset")
  1309. @rx.background
  1310. async def background_task_generator(self):
  1311. """A background task generator that does nothing.
  1312. Yields:
  1313. None
  1314. """
  1315. yield
  1316. def other(self):
  1317. """Some other event that updates the state."""
  1318. self.order.append("other")
  1319. def _private_method(self):
  1320. """Some private method that updates the state."""
  1321. self.order.append("private")
  1322. async def bad_chain1(self):
  1323. """Test that a background task cannot be chained."""
  1324. await self.background_task()
  1325. async def bad_chain2(self):
  1326. """Test that a background task generator cannot be chained."""
  1327. async for _foo in self.background_task_generator():
  1328. pass
  1329. @pytest.mark.asyncio
  1330. async def test_background_task_no_block(mock_app: rx.App, token: str):
  1331. """Test that a background task does not block other events.
  1332. Args:
  1333. mock_app: An app that will be returned by `get_app()`
  1334. token: A token.
  1335. """
  1336. router_data = {"query": {}}
  1337. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1338. async for update in rx.app.process( # type: ignore
  1339. mock_app,
  1340. Event(
  1341. token=token,
  1342. name=f"{BackgroundTaskState.get_name()}.background_task",
  1343. router_data=router_data,
  1344. payload={},
  1345. ),
  1346. sid="",
  1347. headers={},
  1348. client_ip="",
  1349. ):
  1350. # background task returns empty update immediately
  1351. assert update == StateUpdate()
  1352. # wait for the coroutine to start
  1353. await asyncio.sleep(0.5 if CI else 0.1)
  1354. assert len(mock_app.background_tasks) == 1
  1355. # Process another normal event
  1356. async for update in rx.app.process( # type: ignore
  1357. mock_app,
  1358. Event(
  1359. token=token,
  1360. name=f"{BackgroundTaskState.get_name()}.other",
  1361. router_data=router_data,
  1362. payload={},
  1363. ),
  1364. sid="",
  1365. headers={},
  1366. client_ip="",
  1367. ):
  1368. # other task returns delta
  1369. assert update == StateUpdate(
  1370. delta={
  1371. BackgroundTaskState.get_name(): {
  1372. "order": [
  1373. "background_task:start",
  1374. "other",
  1375. ],
  1376. }
  1377. }
  1378. )
  1379. # Explicit wait for background tasks
  1380. for task in tuple(mock_app.background_tasks):
  1381. await task
  1382. assert not mock_app.background_tasks
  1383. assert (await mock_app.state_manager.get_state(token)).order == [
  1384. "background_task:start",
  1385. "other",
  1386. "background_task:stop",
  1387. "other",
  1388. "private",
  1389. ]
  1390. @pytest.mark.asyncio
  1391. async def test_background_task_reset(mock_app: rx.App, token: str):
  1392. """Test that a background task calling reset is protected by the state proxy.
  1393. Args:
  1394. mock_app: An app that will be returned by `get_app()`
  1395. token: A token.
  1396. """
  1397. router_data = {"query": {}}
  1398. mock_app.state_manager.state = mock_app.state = BackgroundTaskState
  1399. async for update in rx.app.process( # type: ignore
  1400. mock_app,
  1401. Event(
  1402. token=token,
  1403. name=f"{BackgroundTaskState.get_name()}.background_task_reset",
  1404. router_data=router_data,
  1405. payload={},
  1406. ),
  1407. sid="",
  1408. headers={},
  1409. client_ip="",
  1410. ):
  1411. # background task returns empty update immediately
  1412. assert update == StateUpdate()
  1413. # Explicit wait for background tasks
  1414. for task in tuple(mock_app.background_tasks):
  1415. await task
  1416. assert not mock_app.background_tasks
  1417. assert (await mock_app.state_manager.get_state(token)).order == [
  1418. "reset",
  1419. ]
  1420. @pytest.mark.asyncio
  1421. async def test_background_task_no_chain():
  1422. """Test that a background task cannot be chained."""
  1423. bts = BackgroundTaskState()
  1424. with pytest.raises(RuntimeError):
  1425. await bts.bad_chain1()
  1426. with pytest.raises(RuntimeError):
  1427. await bts.bad_chain2()
  1428. def test_mutable_list(mutable_state):
  1429. """Test that mutable lists are tracked correctly.
  1430. Args:
  1431. mutable_state: A test state.
  1432. """
  1433. assert not mutable_state.dirty_vars
  1434. def assert_array_dirty():
  1435. assert mutable_state.dirty_vars == {"array"}
  1436. mutable_state._clean()
  1437. assert not mutable_state.dirty_vars
  1438. # Test all list operations
  1439. mutable_state.array.append(42)
  1440. assert_array_dirty()
  1441. mutable_state.array.extend([1, 2, 3])
  1442. assert_array_dirty()
  1443. mutable_state.array.insert(0, 0)
  1444. assert_array_dirty()
  1445. mutable_state.array.pop()
  1446. assert_array_dirty()
  1447. mutable_state.array.remove(42)
  1448. assert_array_dirty()
  1449. mutable_state.array.clear()
  1450. assert_array_dirty()
  1451. mutable_state.array += [1, 2, 3]
  1452. assert_array_dirty()
  1453. mutable_state.array.reverse()
  1454. assert_array_dirty()
  1455. mutable_state.array.sort()
  1456. assert_array_dirty()
  1457. mutable_state.array[0] = 666
  1458. assert_array_dirty()
  1459. del mutable_state.array[0]
  1460. assert_array_dirty()
  1461. # Test nested list operations
  1462. mutable_state.array[0] = [1, 2, 3]
  1463. assert_array_dirty()
  1464. mutable_state.array[0].append(4)
  1465. assert_array_dirty()
  1466. assert isinstance(mutable_state.array[0], MutableProxy)
  1467. # Test proxy returned from __iter__
  1468. mutable_state.array = [{}]
  1469. assert_array_dirty()
  1470. assert isinstance(mutable_state.array[0], MutableProxy)
  1471. for item in mutable_state.array:
  1472. assert isinstance(item, MutableProxy)
  1473. item["foo"] = "bar"
  1474. assert_array_dirty()
  1475. def test_mutable_dict(mutable_state):
  1476. """Test that mutable dicts are tracked correctly.
  1477. Args:
  1478. mutable_state: A test state.
  1479. """
  1480. assert not mutable_state.dirty_vars
  1481. def assert_hashmap_dirty():
  1482. assert mutable_state.dirty_vars == {"hashmap"}
  1483. mutable_state._clean()
  1484. assert not mutable_state.dirty_vars
  1485. # Test all dict operations
  1486. mutable_state.hashmap.update({"new_key": 43})
  1487. assert_hashmap_dirty()
  1488. assert mutable_state.hashmap.setdefault("another_key", 66) == "another_value"
  1489. assert_hashmap_dirty()
  1490. assert mutable_state.hashmap.setdefault("setdefault_key", 67) == 67
  1491. assert_hashmap_dirty()
  1492. assert mutable_state.hashmap.setdefault("setdefault_key", 68) == 67
  1493. assert_hashmap_dirty()
  1494. assert mutable_state.hashmap.pop("new_key") == 43
  1495. assert_hashmap_dirty()
  1496. mutable_state.hashmap.popitem()
  1497. assert_hashmap_dirty()
  1498. mutable_state.hashmap.clear()
  1499. assert_hashmap_dirty()
  1500. mutable_state.hashmap["new_key"] = 42
  1501. assert_hashmap_dirty()
  1502. del mutable_state.hashmap["new_key"]
  1503. assert_hashmap_dirty()
  1504. if sys.version_info >= (3, 9):
  1505. mutable_state.hashmap |= {"new_key": 44}
  1506. assert_hashmap_dirty()
  1507. # Test nested dict operations
  1508. mutable_state.hashmap["array"] = []
  1509. assert_hashmap_dirty()
  1510. mutable_state.hashmap["array"].append(1)
  1511. assert_hashmap_dirty()
  1512. mutable_state.hashmap["dict"] = {}
  1513. assert_hashmap_dirty()
  1514. mutable_state.hashmap["dict"]["key"] = 42
  1515. assert_hashmap_dirty()
  1516. mutable_state.hashmap["dict"]["dict"] = {}
  1517. assert_hashmap_dirty()
  1518. mutable_state.hashmap["dict"]["dict"]["key"] = 43
  1519. assert_hashmap_dirty()
  1520. # Test proxy returned from `setdefault` and `get`
  1521. mutable_value = mutable_state.hashmap.setdefault("setdefault_mutable_key", [])
  1522. assert_hashmap_dirty()
  1523. assert mutable_value == []
  1524. assert isinstance(mutable_value, MutableProxy)
  1525. mutable_value.append("foo")
  1526. assert_hashmap_dirty()
  1527. mutable_value_other_ref = mutable_state.hashmap.get("setdefault_mutable_key")
  1528. assert isinstance(mutable_value_other_ref, MutableProxy)
  1529. assert mutable_value is not mutable_value_other_ref
  1530. assert mutable_value == mutable_value_other_ref
  1531. assert not mutable_state.dirty_vars
  1532. mutable_value_other_ref.append("bar")
  1533. assert_hashmap_dirty()
  1534. # `pop` should NOT return a proxy, because the returned value is no longer in the dict
  1535. mutable_value_third_ref = mutable_state.hashmap.pop("setdefault_mutable_key")
  1536. assert not isinstance(mutable_value_third_ref, MutableProxy)
  1537. assert_hashmap_dirty()
  1538. mutable_value_third_ref.append("baz")
  1539. assert not mutable_state.dirty_vars
  1540. # Unfortunately previous refs still will mark the state dirty... nothing doing about that
  1541. assert mutable_value.pop()
  1542. assert_hashmap_dirty()
  1543. def test_mutable_set(mutable_state):
  1544. """Test that mutable sets are tracked correctly.
  1545. Args:
  1546. mutable_state: A test state.
  1547. """
  1548. assert not mutable_state.dirty_vars
  1549. def assert_set_dirty():
  1550. assert mutable_state.dirty_vars == {"test_set"}
  1551. mutable_state._clean()
  1552. assert not mutable_state.dirty_vars
  1553. # Test all set operations
  1554. mutable_state.test_set.add(42)
  1555. assert_set_dirty()
  1556. mutable_state.test_set.update([1, 2, 3])
  1557. assert_set_dirty()
  1558. mutable_state.test_set.remove(42)
  1559. assert_set_dirty()
  1560. mutable_state.test_set.discard(3)
  1561. assert_set_dirty()
  1562. mutable_state.test_set.pop()
  1563. assert_set_dirty()
  1564. mutable_state.test_set.intersection_update([1, 2, 3])
  1565. assert_set_dirty()
  1566. mutable_state.test_set.difference_update([99])
  1567. assert_set_dirty()
  1568. mutable_state.test_set.symmetric_difference_update([102, 99])
  1569. assert_set_dirty()
  1570. mutable_state.test_set |= {1, 2, 3}
  1571. assert_set_dirty()
  1572. mutable_state.test_set &= {2, 3, 4}
  1573. assert_set_dirty()
  1574. mutable_state.test_set -= {2}
  1575. assert_set_dirty()
  1576. mutable_state.test_set ^= {42}
  1577. assert_set_dirty()
  1578. mutable_state.test_set.clear()
  1579. assert_set_dirty()
  1580. def test_mutable_custom(mutable_state):
  1581. """Test that mutable custom types derived from Base are tracked correctly.
  1582. Args:
  1583. mutable_state: A test state.
  1584. """
  1585. assert not mutable_state.dirty_vars
  1586. def assert_custom_dirty():
  1587. assert mutable_state.dirty_vars == {"custom"}
  1588. mutable_state._clean()
  1589. assert not mutable_state.dirty_vars
  1590. mutable_state.custom.foo = "bar"
  1591. assert_custom_dirty()
  1592. mutable_state.custom.array.append(42)
  1593. assert_custom_dirty()
  1594. mutable_state.custom.hashmap["key"] = 68
  1595. assert_custom_dirty()
  1596. mutable_state.custom.test_set.add(42)
  1597. assert_custom_dirty()
  1598. mutable_state.custom.custom.bar = "baz"
  1599. assert_custom_dirty()
  1600. def test_mutable_backend(mutable_state):
  1601. """Test that mutable backend vars are tracked correctly.
  1602. Args:
  1603. mutable_state: A test state.
  1604. """
  1605. assert not mutable_state.dirty_vars
  1606. def assert_custom_dirty():
  1607. assert mutable_state.dirty_vars == {"_be_custom"}
  1608. mutable_state._clean()
  1609. assert not mutable_state.dirty_vars
  1610. mutable_state._be_custom.foo = "bar"
  1611. assert_custom_dirty()
  1612. mutable_state._be_custom.array.append(42)
  1613. assert_custom_dirty()
  1614. mutable_state._be_custom.hashmap["key"] = 68
  1615. assert_custom_dirty()
  1616. mutable_state._be_custom.test_set.add(42)
  1617. assert_custom_dirty()
  1618. mutable_state._be_custom.custom.bar = "baz"
  1619. assert_custom_dirty()
  1620. @pytest.mark.parametrize(
  1621. ("copy_func",),
  1622. [
  1623. (copy.copy,),
  1624. (copy.deepcopy,),
  1625. ],
  1626. )
  1627. def test_mutable_copy(mutable_state, copy_func):
  1628. """Test that mutable types are copied correctly.
  1629. Args:
  1630. mutable_state: A test state.
  1631. copy_func: A copy function.
  1632. """
  1633. ms_copy = copy_func(mutable_state)
  1634. assert ms_copy is not mutable_state
  1635. for attr in ("array", "hashmap", "test_set", "custom"):
  1636. assert getattr(ms_copy, attr) == getattr(mutable_state, attr)
  1637. assert getattr(ms_copy, attr) is not getattr(mutable_state, attr)
  1638. ms_copy.custom.array.append(42)
  1639. assert "custom" in ms_copy.dirty_vars
  1640. if copy_func is copy.copy:
  1641. assert "custom" in mutable_state.dirty_vars
  1642. else:
  1643. assert not mutable_state.dirty_vars
  1644. @pytest.mark.parametrize(
  1645. ("copy_func",),
  1646. [
  1647. (copy.copy,),
  1648. (copy.deepcopy,),
  1649. ],
  1650. )
  1651. def test_mutable_copy_vars(mutable_state, copy_func):
  1652. """Test that mutable types are copied correctly.
  1653. Args:
  1654. mutable_state: A test state.
  1655. copy_func: A copy function.
  1656. """
  1657. for attr in ("array", "hashmap", "test_set", "custom"):
  1658. var_orig = getattr(mutable_state, attr)
  1659. var_copy = copy_func(var_orig)
  1660. assert var_orig is not var_copy
  1661. assert var_orig == var_copy
  1662. # copied vars should never be proxies, as they by definition are no longer attached to the state.
  1663. assert not isinstance(var_copy, MutableProxy)
  1664. def test_duplicate_substate_class(duplicate_substate):
  1665. with pytest.raises(ValueError):
  1666. duplicate_substate()