test_state.py 62 KB

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