test_state.py 67 KB

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