1
0

test_state.py 74 KB

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